import { element } from 'protractor'
import { style } from '@angular/animations'
import { NotificationService } from '../../shared/utils/notification.service'
import { Component, OnInit } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { config } from '../../shared/smartadmin.config'

import 'script-loader!select2/dist/js/select2.min.js'

import 'assets/js/select2-zh-CN.js'

declare var $: any
declare var BMap: any
declare var echarts: any
declare var Viewer: any
@Component({
  selector: 'sa-fault',
  templateUrl: './fault.component.html',
  styleUrls: ['./fault.css']
})
export class FaultComponent implements OnInit {
  factoryvalidatorOptions = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      companyName: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择公司名称'
          }
          // remote: {
          // 	message: '此厂区限制已存在，请重新添加!',
          //     url: config.BaseURL+"factoryLimit/validateCompanyId.html",
          //     data: function(validator) {
          //         return {
          //             companyId : $("#selectCompanyName").val()
          //         };
          //     },
          // }
        }
      },
      selfTimeInputId: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择时间段'
          }
        }
      }
    }
  }
  fromType: any = ''
  tableData = [] //table数据
  totalCount: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  searchKey: string = '' //搜索keyword
  btnData: any = []
  resourceAdd: boolean = false
  resourceEdit: boolean = false
  resourceDeleteBatch: boolean = false
  resourceImport: boolean = false //导入按钮权限
  faultTypeName: string = '' //查询故障类型参数
  isPush: string = '' //是否推送
  repairedStatus: string = '0' //查询故障状态参数
  selectedCompanyName: string = '' //查询公司参数
  selectedCompanyId: string = '' //查询公司参数
  deviceId: string = '' //查询设备参数
  carNumber: string = '' //查询车牌号码参数
  userList: any = [] //用户数据List
  userName: string = '' //查询用户参数
  userId: string = '' //查询用户id参数
  startTime = '' //查询开始时间参数
  endTime = '' //查询结束时间参数
  dateType: string = '1' //时间类型
  sortType: string = '2' //时间类型
  serviceType: string = '' //服务到期
  useTypeL1: string = '' //车辆分类一级
  useTypeL2: string = '' //车辆分类二级
  companyData: any = {} // 和子组件通信的数据

  allChecked: boolean = false //table全选状态值
  selected: any[] = [] //row选择的数据
  rowId: string = '' //批量进厂限制
  lgisPush: any = '0' //是否进厂限制 默认不限制
  isPushTime: number = 6
  isPushTimeFlag: string = ''
  faultTypeArr: any = [
    {
      type: 1,
      text: '传感器'
    },
    {
      type: 2,
      text: 'GPS'
    },
    {
      type: 3,
      text: '线材'
    },
    {
      type: 4,
      text: '主机'
    },
    {
      type: 5,
      text: '其他'
    }
  ]
  waitingRepairCarTopList: any = [] //待维修统计排名
  topNumber: string = '10' //默认top10
  curBtn: string = '' //排名高亮按钮;默认一周
  topTimeID: any = {
    picker1: 'datetimepicker5',
    picker2: 'datetimepicker6'
  } //排名试驾元素ID
  topStartTime: string = '' //排名开始时间
  topEndTime: string = '' //排名结束时间
  modal: any = {
    //图片弹窗
    picture: '',
    active: '', //激活的图片
    activeNum: null //激活的图片下标
  }
  inputCompanyTreeCarData: any = {} //车辆运行状态模块跳转该页面传递过来的参数
  // 设置厂区在线的参数
  onlineSetCompanyId: string = '' // 公司
  onlineSetCompanyName: string = '' // 公司
  factoryOnlinePageSize: number = 10 // 厂区在线表的页的条数
  factoryOnlineCurPage: any = 1 // 当前页码
  factoryOnlinetotalCount: number = 0 // 分页总条数
  factoryOnlineSearchKey: string = '' // 关键字搜素
  factoryOnlineTableData: any = [] // 厂区设置在线的表单数据
  selfTimeInputId: string = '' //自定义时间段input的id值
  selfTimeData: any = [] //自定义时间段时间校验缓存集合
  startTimeSelected: number
  endTimeSelected: number
  difValue: number
  timeSlot: string = '' //提交的时间段
  hourList = [
    {
      index: 0
    },
    {
      index: 1
    },
    {
      index: 2
    },
    {
      index: 3
    },
    {
      index: 4
    },
    {
      index: 5
    },
    {
      index: 6
    },
    {
      index: 7
    },
    {
      index: 8
    },
    {
      index: 9
    },
    {
      index: 10
    },
    {
      index: 11
    },
    {
      index: 12
    },
    {
      index: 13
    },
    {
      index: 14
    },
    {
      index: 15
    },
    {
      index: 16
    },
    {
      index: 17
    },
    {
      index: 18
    },
    {
      index: 19
    },
    {
      index: 20
    },
    {
      index: 21
    },
    {
      index: 22
    },
    {
      index: 23
    }
  ]
  jumpData: any // 跳转页面接收到的数据
  //  initDateRange: any = {}// 时间组件需要渲染的值
  companyParentList: any = [] //公司树的存储值
  provinceId: string = '' //省份ID
  provinceList: any = [] //省份列表数据
  constructor(
    private jsonApiService: JsonApiService,
    private notificationService: NotificationService,
    private router: Router,
    private activatedRoute: ActivatedRoute
  ) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.curPage = queryParams.nowPage == undefined ? 1 : queryParams.nowPage
      this.inputCompanyTreeCarData = JSON.parse(common.getCookie('jumpRepairedDeviceList'))
      if (common.getCookie('jumpTo/device-management/fault')) {
        this.jumpData = JSON.parse(common.getCookie('jumpTo/device-management/fault'))
        this.companyData.companyId = this.selectedCompanyId = this.jumpData.companyId
        this.companyData.companyName = this.selectedCompanyName = this.jumpData.companyName
      }

      // 从信息汇总跳转过来的数据
      const summaryInfoParams = JSON.parse(common.getCookie('jumpFromSummaryInfo'))
      if (summaryInfoParams) {
        this.searchKey = summaryInfoParams.deviceId
      }
    })
  }
  //父级公司树请求
  ngInitCompany() {
    this.jsonApiService.http('company/companytree.html', null).subscribe(data => {
      this.companyParentList = data
    })
  }
  // 获取省份列表
  getProvinceList() {
    this.jsonApiService.http_get('region/getChinessProvince.html').subscribe(data => {
      if (data.success) {
        this.provinceList = data.data
      }
    })
  }
  ngOnInit() {
    this.ngInitCompany()
    this.getProvinceList() //请求省份数据
    this.initAllUser().then(() => {
      this.selectUserName()
    })
    this.initAllOperator().then(() => {
      this.selectOperator()
    })
    this.initWhitelistCarSelect() //初始化select 2 榜单

    if (this.inputParam.length == 0) {
      this.querySensor()
    } // 请求传感器列表接口

    this.initBtn()
    this.reaustHeader() //请求表头
    this.reviewDate() // 数据的回显

    // 传感器白名单
    if (common.getCookie('__OPEN_WHITELIST__')) {
      const source = common.getCookie('__OPEN_WHITELIST__')
      /**
       * TODO 打开白名单弹框
       *  */
      console.log(source);
      common.clearCookie('__OPEN_WHITELIST__')
      setTimeout(() => {
        $('#sensorWhitelistTriggerBtn').click()
      }, 200)
    }

    if (common.getCookie('jumpTo/device-management/fault')) {
      this.initDate().then(() => {
        $('#datetimepicker3').val(this.jumpData.startTime)
        $('#datetimepicker4').val(this.jumpData.endTime) //当前时间
        this.startTime = $('#datetimepicker3').val()
        this.endTime = $('#datetimepicker4').val()
        this.dateType = '2'
        setTimeout(() => {
          this.load()
        }, 100)
      })
      common.clearCookie('jumpTo/device-management/fault')
    } else if (common.getCookie('jumpRepairedDeviceList')) {
      this.searchKey = this.inputCompanyTreeCarData.carNumber
      this.repairedStatus = this.inputCompanyTreeCarData.repairedStatus
      this.dateType = this.inputCompanyTreeCarData.dateType
      $('#datetimepicker3').val(this.inputCompanyTreeCarData.startTime)
      $('#datetimepicker4').val(this.inputCompanyTreeCarData.endTime) //当前时间
      this.startTime = $('#datetimepicker3').val()
      this.endTime = $('#datetimepicker4').val()
      setTimeout(() => {
        this.load()
      }, 550)
      common.clearCookie('jumpRepairedDeviceList')
    } else if (common.getCookie('jumpFromSummaryInfo')) {
      this.initDate().then(() => {
        $('#datetimepicker3').val('')
        $('#datetimepicker4').val('') //当前时间
        this.startTime = $('#datetimepicker3').val()
        this.endTime = $('#datetimepicker4').val()
        setTimeout(() => {
          this.load()
        }, 100)
      })
      common.clearCookie('jumpFromSummaryInfo')
    } else {
      this.initDate().then(() => {
        this.load()
      })
    }
  }

  //请求传感器类型的接口
  querySensor() {
    this.jsonApiService.http('sensorManage/querySensorList.html', '').subscribe(data => {
      if (data.success) {
        this.inputParam = data.data
      }
    })
  }
  ngOnDestroy() {
    document.onclick = null
  }
  topDateSelect(type) {
    this.curBtn = type
    let curTime = new Date()
    let curDate = common.getTimeDay(curTime)
    let currentMonthDays = new Date().getDate() - 1
    let startTime, endTime
    switch (type) {
      case '1':
        this.startTime = curDate + ' 00:00:00'
        this.endTime = curDate + ' 23:59:59'
        break
      case '2':
        this.startTime = common.getTimeDay(new Date(curTime.getTime() - 3600 * 24 * 1000 * 6)) + ' 00:00:00'
        this.endTime = curDate + ' 23:59:59'
        break
      case '3':
        this.startTime =
          common.getTimeDay(new Date(curTime.getTime() - 3600 * 24 * 1000 * currentMonthDays)) + ' 00:00:00'
        this.endTime = curDate + ' 23:59:59'
        break
      default:
        this.startTime = ''
        this.endTime = ''
        break
    }
    $('#datetimepicker5').val(this.startTime).change()
    $('#datetimepicker6').val(this.endTime).change()
    this.initCarWaitingRepairTop()
  }

  //待维修车辆Top排名
  carWaitingRepairTop(modal) {
    modal.show()
    this.curBtn = ''
    this.topNumber = '10'
    this.initCarWaitingRepairTop()
  }
  // 数据导出
  exportData() {
    const param = {
      userName: this.userName, //用户名
      faultTypeName: this.faultTypeName, //故障类型
      repairedStatus: this.repairedStatus, //故障状态
      dateType: this.dateType, //时间类型
      sortType: this.sortType,
      startTime: this.startTime, //开始时间
      endTime: this.endTime, //结束时间
      searchKey: this.searchKey, //搜索内容
      companyId: this.selectedCompanyId, //选择的公司ID
      deviceId: this.deviceId, //设备ID
      isPush: this.isPush, //是否推送
      isByAuth: false, //数据做权限控制
      useTypeL2: this.useTypeL2,
      provinceId: this.provinceId,
      serviceType: this.serviceType
    }
    let timeCheck = common.correctTime(param, ['dateType', 'sortType', 'isByAuth'])
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message)
      return
    }
    common.exprotDataFile(param, 'param', config.BaseURL + 'deviceRepaired/exportDeviceRepairedList.html')
  }
  //排名回调
  topNumberChange() {
    this.initCarWaitingRepairTop()
  }
  //待维修车辆Top排名数据拉取
  initCarWaitingRepairTop() {
    let data = {
      searchKey: this.searchKey,
      companyId: this.selectedCompanyId,
      deviceId: this.deviceId,
      userName: this.userName,
      faultTypeName: this.faultTypeName,
      repairedStatus: this.repairedStatus,
      dateType: this.dateType,
      startDate: this.startTime,
      endDate: this.endTime,
      isPush: this.isPush, //是否推送
      isByAuth: false,
      useTypeL2: this.useTypeL2
    }
    let reqdata = 'param=' + JSON.stringify(data) + '&topNumber=' + this.topNumber
    this.jsonApiService.http('deviceRepaired/countDataRecordForTop.html', reqdata).subscribe(result => {
      if (result.data && result.success) {
        this.waitingRepairCarTopList = []
        this.waitingRepairCarTopList = result.data
        //				let temArr: any = result.data;
        //				for (let key in temArr) {
        //					let obj = {
        //						text: key,
        //						value: temArr[key]
        //					}
        //					this.waitingRepairCarTopList.push(obj);
        //				}
      }
    })
  }
  // 跳转详情
  faultDetail(modal, item, startTime, endTime) {
    this.closeModal(modal)
    this.searchKey = item.carNumber
    this.load()
  }
  waitingRepairTopExport() {
    let data = {
      searchKey: this.searchKey,
      companyId: this.selectedCompanyId,
      deviceId: this.deviceId,
      userName: this.userName,
      faultTypeName: this.faultTypeName,
      repairedStatus: this.repairedStatus,
      startDate: this.startTime,
      endDate: this.endTime,
      isPush: this.isPush, //是否推送
      isByAuth: false,
      useTypeL2: this.useTypeL2
    }
    var form = $('<form>') //定义一个form表单
    form.attr('style', 'display:none')
    form.attr('target', '')
    form.attr('method', 'post')
    form.attr('action', config.BaseURL + 'deviceRepaired/countDataRecordForTopExport.html')
    var fileInput = $('<input>')
    fileInput.attr('type', 'hidden')
    fileInput.attr('id', 'fileName') //设置属性的名字
    fileInput.attr('name', 'param') //设置属性的名字
    fileInput.attr('value', JSON.stringify(data)) //设置属性的值
    var fileInput2 = $('<input>')
    fileInput2.attr('type', 'hidden')
    fileInput2.attr('id', 'fileName2') //设置属性的名字
    fileInput2.attr('name', 'topNumber') //设置属性的名字
    fileInput2.attr('value', this.topNumber) //设置属性的值
    $('body').append(form) //将表单放置在web中
    form.append(fileInput)
    form.append(fileInput2)
    form.submit() //表单提交
  }
  //初始化时间
  initDate() {
    var that = this
    return new Promise(function (resolve, reject) {
      System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
        System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
          $('#datetimepicker3')
            .datetimepicker({
              format: 'yyyy-mm-dd hh:ii:ss',
              language: 'zh-CN',
              autoclose: true
            })
            .on('changeDate', function (e) {
              var date = e.date
              var time = common.getTimeMmss(date)
              that.startTime = time
              $('#datetimepicker4').datetimepicker('setStartDate', time)
            })
          $('#datetimepicker4')
            .datetimepicker({
              format: 'yyyy-mm-dd hh:ii:ss',
              language: 'zh-CN',
              autoclose: true
            })
            .on('changeDate', function (e) {
              var date = e.date
              var time = common.getTimeMmss(date)
              that.endTime = time
              $('#datetimepicker3').datetimepicker('setEndDate', time)
            })
          var date = new Date()
          let time1 = common.getTimeMmss(date)
          $('#datetimepicker4').val(time1) //当前时间
          that.endTime = time1
          date.setDate(date.getDate() - 31) //设置前31天
          let time2 = common.getTimeMmss(date)
          $('#datetimepicker3').val(time2)
          that.startTime = time2

          //不良记录的时间
          $('#returnTime')
            .datetimepicker({
              //时间插件
              format: 'yyyy-mm-dd hh:ii:ss',
              language: 'zh-CN',
              autoclose: true
            })
            .on('changeDate', function (e) {
              var date = e.date
              if (!date) {
                return
              }
              var time = common.getTimeMmss(date)
              that.recordDetailFrom.returnTime = time
            })

          // $("#returnTime").datetimepicker("setEndDate", date);

          $('#productTime')
            .datetimepicker({
              //时间插件
              format: 'yyyy-mm-dd hh:ii:ss',
              language: 'zh-CN',
              autoclose: true
            })
            .on('changeDate', function (e) {
              var date = e.date
              if (!date) {
                return
              }
              var time = common.getTimeMmss(date)
              that.recordDetailFrom.productTime = time
            })

          // $("#productTime").datetimepicker("setEndDate", date);

          // 传感器白名单
          $('#sensorWhitelistDatepicker1')
            .datetimepicker({
              //时间插件
              format: 'yyyy-mm-dd hh:ii:ss',
              language: 'zh-CN',
              autoclose: true
            })
            .on('changeDate', function (e) {
              const date = e.date
              if (!date) {
                return
              }
              that.sensorWhitelistParams.startTime = common.getTimeMmss(date)
            })

          $('#sensorWhitelistDatepicker2')
            .datetimepicker({
              //时间插件
              format: 'yyyy-mm-dd hh:ii:ss',
              language: 'zh-CN',
              autoclose: true
            })
            .on('changeDate', function (e) {
              const date = e.date
              if (!date) {
                return
              }
              that.sensorWhitelistParams.endTime = common.getTimeMmss(date)
            })


          resolve(null)
        })
      })
    })
  }
  // 数据的回显
  reviewDate() {
    // 判断是否需要回显
    var deviceFaultDataString = sessionStorage.getItem('deviceFaultData')
    if (deviceFaultDataString) {
      var deviceFaultData = JSON.parse(deviceFaultDataString)
      this.companyData = deviceFaultData
      this.selectedCompanyId = deviceFaultData['companyId']
      this.selectedCompanyName = deviceFaultData['companyName']
      this.deviceId = deviceFaultData['deviceId']
      this.carNumber = deviceFaultData['carNumber']
      this.useTypeL2 = deviceFaultData['useTypeL2']
      this.useTypeL1 = deviceFaultData['useTypeL1']
      this.userName = deviceFaultData['userName']
      this.userId = deviceFaultData['userId']
      this.faultTypeName = deviceFaultData['faultTypeName']
      this.isPush = deviceFaultData['isPush']
      this.repairedStatus = deviceFaultData['repairedStatus']
      this.dateType = deviceFaultData['dateType']
      this.sortType = deviceFaultData['sortType']
      this.serviceType = deviceFaultData['serviceType']
      this.startTime = deviceFaultData['startTime']
      this.endTime = deviceFaultData['endTime']
      $('#userNameSelect2').val(this.userName).trigger('change')
      $('#datetimepicker3').val(this.startTime)
      $('#datetimepicker4').val(this.endTime)
      sessionStorage.removeItem('deviceFaultData')
    }
  }
  //删除所选时间
  del_date() {
    this.startTime = ''
    this.endTime = ''
    $('#datetimepicker3').val('').change()
    $('#datetimepicker4').val('').change()
    $('#datetimepicker4').datetimepicker('setStartDate', null)
    $('#datetimepicker3').datetimepicker('setEndDate', null)
  }
  //擦除用户所选值
  delUserName() {
    this.userName = ''
    this.userId = ''
    //采用简单粗暴的方法清除;官方推荐的方法失效
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#userNameSelect2').val('')
    $('#select2-userNameSelect2-container').empty()
    $('#select2-userNameSelect2-container').attr('title', '')
    $('#select2-userNameSelect2-container').prepend(str)
  }

  //擦除用户所选值
  delOperator() {
    this.operatorName = ''
    //采用简单粗暴的方法清除;官方推荐的方法失效
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#operatorSelect2').val('')
    $('#select2-operatorSelect2-container').empty()
    $('#select2-operatorSelect2-container').attr('title', '')
    $('#select2-operatorSelect2-container').prepend(str)
  }
  //初始化select2 选项
  selectUserName() {
    const that = this

    $('#userNameSelect2')
      .select2({
        language: 'zh-CN',
        placeholder: '请选择',
        allowClear: true,
        data: this.userList, //为Select添加数据
        templateResult: this.formatRepo
      })
      .on('select2:select', function (e) {
        var data = e.params.data
        that.userName = data.text
        that.userId = data.id
      })

    //获取推送APP 推送人
    $('#pushUserNameSelect2')
      .select2({
        language: 'zh-CN',
        placeholder: '请选择',
        allowClear: true,
        data: this.userList, //为Select添加数据
        templateResult: this.formatRepo
      })
      .on('select2:select', function (e) {
        var data = e.params.data
        that.pushUserName = data.text
        that.pushName = data.userName
      })
  }

  selectOperator() {
    const that = this
    $('#operatorSelect2')
      .select2({
        language: 'zh-CN',
        placeholder: '请选择',
        allowClear: true,
        data: this.operatorList, //为Select添加数据
        // 自定义 options 展示样式
        templateResult: state => {
          const $state = $('<span><i class="fa fa-user green"></i>&nbsp;&nbsp;' + state.operatorName + '</span>')
          return $state
        }
      })
      .on('select2:select', function (e) {
        const data = e.params.data
        that.operatorName = data.operatorName
      })
  }
  //select2 格式回调函数
  formatRepo(state) {
    if (!state.id) {
      return state.text
    }
    var $state = $('<span><i class="fa fa-user green"></i>&nbsp;&nbsp;' + state.text + '</span>')
    return $state
  }
  //拉取
  initAllUser() {
    var that = this
    return new Promise(function (resolve) {
      that.jsonApiService.http('user/getAllUserList.html', null).subscribe(data => {
        if (data.success) {
          var userList = data.data
          var selectdata = []
          for (var i = 0; i < userList.length; i++) {
            var obj = {
              id: userList[i].id,
              text: userList[i].name,
              userName: userList[i].userName
            }
            selectdata[i] = obj
          }
        }
        that.userList = selectdata
        resolve(data)
      })
    })
  }

  // 厂区运维负责人列表
  operatorList = []

  operatorName = '' // 厂区负责人

  //拉取
  initAllOperator() {
    const that = this
    return new Promise(function (resolve) {
      that.jsonApiService.http_get('projectPeople/getOperationUserList.html').subscribe(data => {
        if (data.success) {
          that.operatorList = data.data.map(el => ({
            id: el.id, // 必须要有 id，不能许选中
            operatorName: el.name,
            text: el.name // text 是选中后显示的值
          }))
        }
        resolve(data)
      })
    })
  }
  //table刷新
  refresh() {
    this.load()
  }
  //初始化权限按钮
  initBtn() {
    this.btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_device-management:fault')))
    if (!this.btnData) {
      return
    }
    for (let item of this.btnData) {
      if (item.sourceKey === 'equipmentFailure:add' && item.parentId) {
        this.resourceAdd = true
      }
      if (item.sourceKey === 'equipmentFailure:edit' && item.parentId) {
        this.resourceEdit = true
      }
      if (item.sourceKey === 'equipmentFailure:del' && item.parentId) {
        this.resourceDeleteBatch = true
      }
      if (item.sourceKey === 'equipmentFailure:import' && item.parentId) {
        this.resourceImport = true
      }
    }
  }
  //表格搜索
  table_search() {
    this.curPage = 1
    this.searchKey = common.stringTrim(this.searchKey)
    this.load()
  }
  //初始化加载list数据
  load() {
    this.startTime = $('#datetimepicker3').val()
    this.endTime = $('#datetimepicker4').val()
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        dateType: this.dateType,
        sortType: this.sortType,
        searchKey: this.searchKey,
        companyId: this.selectedCompanyId,
        deviceId: this.deviceId,
        userName: this.userName,
        faultTypeName: this.faultTypeName,
        repairedStatus: this.repairedStatus,
        startDate: this.startTime,
        endDate: this.endTime,
        isPush: this.isPush, //是否推送
        isByAuth: false,
        useTypeL2: this.useTypeL2,
        operatorName: this.operatorName, // 厂区运维负责人
        provinceId: this.provinceId,
        serviceType: this.serviceType
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('deviceRepaired/findDeviceRepairedList.html', reqdata).subscribe(result => {
      this.selected = []
      this.tableData = result.exhibitDatas || []
      let currentTime = new Date()
      if (result.exhibitDatas.length > 0) {
        for (var i = 0; i < result.exhibitDatas.length; i++) {
          if (result.exhibitDatas[i].createTime && result.exhibitDatas[i].repairedTime) {
            var d1 = result.exhibitDatas[i].createTime.replace(/\-/g, '/')
            var date1 = new Date(d1)
            var d2 = result.exhibitDatas[i].repairedTime.replace(/\-/g, '/')
            var date2 = new Date(d2)
            var s1 = date1.getTime(),
              s2 = date2.getTime()
            var resTime = common.secondToDate((s2 - s1) / 1000)
            this.tableData[i].responseTime = resTime
          }
          result.exhibitDatas[i].restrictTimeFlag = false
          if (result.exhibitDatas[i].restrictTime) {
            if (
              common.mmsstoTimestamp(common.getNowTime()) -
              common.mmsstoTimestamp(result.exhibitDatas[i].restrictTime) <
              0
            ) {
              result.exhibitDatas[i].restrictTimeFlag = true
            }
          }
        }
      }
      // this.tableData = result.exhibitDatas || [];
      this.tableData.map(item => (item.callDuration = common.secondToDate(item.callDuration)))
      this.totalCount = result.recordCount
    })
  }
  //分页回调
  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
  //新建
  new_fault() {
    this.router.navigate(['/device-management/fault/fault-page'], { queryParams: { type: 'new' } })
  }
  //编辑页面
  updata_fault(row) {
    // 存储完再跳转路由
    var deviceFaultData = {}
    // 给本地赋值
    deviceFaultData['companyId'] = this.selectedCompanyId // 公司id
    deviceFaultData['companyName'] = this.selectedCompanyName // 公司名字
    deviceFaultData['deviceId'] = this.deviceId //车牌号
    deviceFaultData['carNumber'] = this.carNumber
    deviceFaultData['useTypeL2'] = this.useTypeL2 //车辆分类
    deviceFaultData['useTypeL1'] = this.useTypeL1
    deviceFaultData['userName'] = this.userName //用户信息
    deviceFaultData['userId'] = this.userId
    deviceFaultData['faultTypeName'] = this.faultTypeName // 进厂限制
    deviceFaultData['isPush'] = this.isPush // 故障类型
    deviceFaultData['repairedStatus'] = this.repairedStatus // 故障状态
    deviceFaultData['dateType'] = this.dateType // 时间类型
    deviceFaultData['sortType'] = this.sortType //升序降序
    deviceFaultData['startTime'] = this.startTime // 开始时间
    deviceFaultData['endTime'] = this.endTime // 结束时间
    deviceFaultData['serviceType'] = this.serviceType // 服务到期
    sessionStorage.setItem('deviceFaultData', JSON.stringify(deviceFaultData))
    this.router.navigate(['/device-management/fault/fault-page'], {
      queryParams: { id: row.id, type: 'edit', nowPage: this.curPage }
    })
  }
  //推送APP
  pushUserName: any = '' //推送人
  pushName: any = '' //英文推送人
  pushUserListId: any = ''
  push_edit(row, modal) {
    this.delPushUserName()
    this.pushUserListId = row.id
    modal.show()
  }
  pushEditModalhide(modal) {
    this.pushUserName = ''
    this.pushName = ''
    this.pushUserListId = ''
    modal.hide()
  }
  pushEditReset(modal) {
    let reqdata = 'id=' + this.pushUserListId + '&userName=' + this.pushName
    this.jsonApiService.http('deviceRepaired/sendMessageToApp.html', reqdata).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        this.load()
        this.pushEditModalhide(modal)
      }
    })
  }
  delPushUserName() {
    this.pushUserName = ''
    this.pushName = ''
    //采用简单粗暴的方法清除;官方推荐的方法失效
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#pushUserNameSelect2').val('')
    $('#select2-pushUserNameSelect2-container').empty()
    $('#select2-pushUserNameSelect2-container').attr('title', '')
    $('#select2-pushUserNameSelect2-container').prepend(str)
  }
  del_fault(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
      let reqdata = 'id=' + row.id
      this.jsonApiService.http('deviceRepaired/delDeviceRepairedById.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.load()
        }
      })
    })
  }
  //公司选中回调
  companySelected(data) {
    this.selectedCompanyId = data.companyId
    this.selectedCompanyName = data.companyName
    this.deviceId = data.deviceId
    this.carNumber = data.carNumber
    this.useTypeL2 = data.useTypeL2
    this.useTypeL1 = data.useTypeL1
    if (!data.companyName) {
      this.serviceType = ''
    }
  }
  beforeImageInfo: any = [] //维修前图片展示
  afterImageInfo: any = [] //维修后图片展示
  imageType: any
  imagesInfo: any = [] //图片展示
  isViewer: boolean = false //默认隐藏
  //显示图片组件
  viewer: any = ''
  //查看照片
  open_img(type, row, val) {
    //1主机 2采集器 3传感器 4线材 5GPS 6其他
    if (type == 'after') {
      this.afterImageInfo = row.afterImageInfo
      this.imageType = '维修后'
      for (var i = 0; i < row.afterImageInfo.length; i++) {
        if (row.afterImageInfo[i].index == 1) {
          row.afterImageInfo[i].title = '主机'
        } else if (row.afterImageInfo[i].index == 2) {
          row.afterImageInfo[i].title = '采集器'
        } else if (row.afterImageInfo[i].index == 3) {
          row.afterImageInfo[i].title = '传感器'
        } else if (row.afterImageInfo[i].index == 4) {
          row.afterImageInfo[i].title = '线材'
        } else if (row.afterImageInfo[i].index == 5) {
          row.afterImageInfo[i].title = 'GPS'
        } else if (row.afterImageInfo[i].index == 6) {
          row.afterImageInfo[i].title = '其他'
        }
        row.afterImageInfo[i].localImg = []
        for (let c = 0; c < row.afterImageInfo[i].imageList.length; c++) {
          let localImg
          if (row.afterImageInfo[i].imageList[c].indexOf('http') == -1) {
            if (row.afterImageInfo[i].imageList[c][0] == '/') {
              localImg = config.BaseURL + row.afterImageInfo[i].imageList[c].substr(1)
            } else {
              localImg = config.BaseURL + row.afterImageInfo[i].imageList[c]
            }
          } else {
            localImg = row.afterImageInfo[i].imageList[c]
          }
          row.afterImageInfo[i].localImg.push(localImg)
        }
      }
      this.imagesInfo = JSON.parse(JSON.stringify(row.afterImageInfo))
    }
    if (type == 'before') {
      this.beforeImageInfo = row.beforeImageInfo
      this.imageType = '维修前'
      for (var j = 0; j < row.beforeImageInfo.length; j++) {
        if (row.beforeImageInfo[j].index == 1) {
          row.beforeImageInfo[j].title = '主机'
        } else if (row.beforeImageInfo[j].index == 2) {
          row.beforeImageInfo[j].title = '采集器'
        } else if (row.beforeImageInfo[j].index == 3) {
          row.beforeImageInfo[j].title = '传感器'
        } else if (row.beforeImageInfo[j].index == 4) {
          row.beforeImageInfo[j].title = '线材'
        } else if (row.beforeImageInfo[j].index == 5) {
          row.beforeImageInfo[j].title = 'GPS'
        } else if (row.beforeImageInfo[j].index == 6) {
          row.beforeImageInfo[j].title = '其他'
        }
        row.beforeImageInfo[j].localImg = []
        for (let c = 0; c < row.beforeImageInfo[j].imageList.length; c++) {
          let localImg
          if (row.beforeImageInfo[j].imageList[c].indexOf('http') == -1) {
            if (row.beforeImageInfo[j].imageList[c][0] == '/') {
              localImg = config.BaseURL + row.beforeImageInfo[j].imageList[c].substr(1)
            } else {
              localImg = config.BaseURL + row.beforeImageInfo[j].imageList[c]
            }
          } else {
            localImg = row.beforeImageInfo[j].imageList[c]
          }

          row.beforeImageInfo[j].localImg.push(localImg)
        }
      }
      this.imagesInfo = JSON.parse(JSON.stringify(row.beforeImageInfo))
    }

    if (this.isViewer && $('.viewer-container').length > 0) {
      this.viewer.destroy()
    }
    event.stopPropagation()
    val.show()
    // if (row.paths.length > 0) {
    // 	this.modal.active = row.paths[0];
    // 	this.modal.activeNum = 0;
    // 	this.modal.picture = row.paths;
    // }
  }
  bigImg: any = '' // 放大的图片
  //图片放大
  bigimg(modal, row) {
    // modal.show();
    this.bigImg = row
    if (this.isViewer && $('.viewer-container').length > 0) {
      System.import('assets/js/viewer/viewer.js').then(() => {
        System.import('assets/js/viewer/bootstrap.bundle.min.js').then(() => {
          System.import('assets/js/viewer/viewer.css').then(() => {
            this.showImg()
          })
        })
      })
    } else {
      this.showImg()
    }
  }
  showImg() {
    var that = this
    var imgList = $('.imagesInfo')[0]
    this.viewer = new Viewer(imgList, {
      url: 'src',
      title: function (image) {
        return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')'
      }
    })
    that.isViewer = true
  }
  //图片hover事件
  switch_img(index) {
    this.modal.activeNum = index
    this.modal.active = this.modal.picture[index]
  }
  //pre
  change_img_left() {
    if (this.modal.activeNum) {
      this.modal.activeNum--
      this.modal.active = this.modal.picture[this.modal.activeNum]
    }
  }
  //next
  change_img_right(e) {
    if (this.modal.activeNum < this.modal.picture.length - 1) {
      this.modal.activeNum++
      this.modal.active = this.modal.picture[this.modal.activeNum]
    }
  }
  //关闭图片弹窗
  imgClose(val) {
    val.hide()
  }
  /**
   * 设备维修记录
   */
  isOpenCalendar: boolean = false
  openRepairedRecord(modal) {
    modal.show()
    this.isOpenCalendar = true
  }
  closeRepairedRecord(modal) {
    modal.hide()
    this.isOpenCalendar = false
  }
  /**
   *  echart图
   */
  activeSelected: any
  startTime_chart: string = ''
  endTime_chart: string = ''
  isChartView: boolean = false
  isMapView: boolean = false
  specifyTime: any = {
    startTime: '',
    endTime: ''
  }
  selectedRow: any
  drawTrackArr: any
  //数据查看
  drawAbnormalChart() {
    if (!this.selectedRow) {
      this.jsonApiService.message('先选择需要查看折线图的车辆')
      return
    }
    if (!this.startTime_chart || !this.endTime_chart) {
      this.jsonApiService.message('时间不能为空')
      return
    }
    let timeCheck = common.correctTimeParams(this.startTime_chart, this.endTime_chart, 0)
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message)
      return
    }
    this.lineParamDeal(this.selectedRow)
  }
  checkAbnormal(row: any) {
    // if (row.repairedStatus == '0') {
    //   if (!row.faultTime) {
    //     this.jsonApiService.message('该设备没有故障时间!')
    //     return
    //   }
    //   let temStartWait = common.mmsstoTimestamp(row.faultTime)
    //   row.startTime = row.faultTime
    //   row.endTime = common.getTimeMmss(new Date(temStartWait + 3 * 24 * 3600 * 1000))
    // } else if (row.repairedStatus == '1') {
    //   let temStartFixed = common.mmsstoTimestamp(row.repairedTime)
    //   row.startTime = common.getTimeMmss(new Date(temStartFixed - 1 * 24 * 3600 * 1000))
    //   row.endTime = common.getTimeMmss(new Date(temStartFixed + 2 * 24 * 3600 * 1000))
    // }
    const { lastUpdateTime } = row
    const lastTimestamp = common.mmsstoTimestamp(lastUpdateTime)
    this.startTime_chart = common.getTimeMmss(new Date(lastTimestamp - 12 * 60 * 60 * 1000))
    this.endTime_chart = common.getTimeMmss(new Date(lastTimestamp + 12 * 60 * 60 * 1000))

    // row对象新增属性
    this.activeSelected = row.id

    this.isChartView = true
    this.specifyTime = {
      startTime: this.startTime_chart,
      endTime: this.endTime_chart
    }
    this.lineParamDeal(row)
  }
  runParent(value) {
    this.drawTrackArr = value
  }
  //折线图时间回调事件
  getSelectChartTime(time) {
    this.startTime_chart = time.startTime
    this.endTime_chart = time.endTime
  }
  showMapView(val) {
    this.isMapView = val
  }

  echartLimitTitle = '限制进厂'
  //获取传感器通道参数
  lineParamDeal(row) {
    let reqdata = 'deviceId=' + row.deviceId
    this.jsonApiService.http('realtime/getRealTimeData.html', reqdata).subscribe(result => {
      if (result.success && result.data) {
        let params = {
          deviceId: row.deviceId,
          startTime: this.startTime_chart,
          endTime: this.endTime_chart,
          coefficient: result.data.coef,
          id: row.id, // 写入 id，设置限制进厂使用
          companyId: row.companyId,
          carNumber: row.carNumber,
          isPush: row.isPush
        }
        this.selectedRow = params
        this.getDeviceBasicInfo()
      }
    })
  }
  closeChart() {
    this.isChartView = false
  }
  /**
   * 统计有故障记录,无故障记录,问题分类部分[注:数据统计]
   */
  totleCount: number //按公司统计:统计所有
  repairCount: number //按公司统计:有故障记录
  waitRepairedCount: number //按公司统计:统计无故障记录
  dataAbnormalCarList: any = [] //问题数据[饼图]
  dataAbnormalCarTotalList: any = [] //问题记录List[table]
  dataAbnormalCarTotal: number //问题总数
  dataRepaireTotalList: any = [] //维修记录List[table]

  //问题分类数据处理
  questionSort(modal) {
    if (!this.selectedCompanyId) {
      this.jsonApiService.message('请选择需要查看的公司!')
      return
    }
    modal.show()
    let data = {
      searchKey: this.searchKey,
      companyId: this.selectedCompanyId,
      deviceId: this.deviceId,
      userName: this.userName,
      faultTypeName: this.faultTypeName,
      repairedStatus: this.repairedStatus,
      dateType: this.dateType,
      sortType: this.sortType,
      startDate: this.startTime,
      endDate: this.endTime,
      isPush: this.isPush, //是否推送
      isByAuth: false,
      useTypeL2: this.useTypeL2,
      serviceType: this.serviceType
    }
    let reqdata = 'param=' + JSON.stringify(data)
    this.jsonApiService.http('deviceRepaired/countRepairedScale.html', reqdata).subscribe(result => {
      let dataRepaired: any = [] //饼图数据
      this.dataRepaireTotalList = []
      this.totleCount = result.data.totleCount //总数
      this.repairCount = result.data.repairCount //有故障记录
      this.waitRepairedCount = this.totleCount - this.repairCount //无故障记录
      dataRepaired.push({ value: result.data.repairCount, name: '有故障记录[车]' })
      dataRepaired.push({ value: this.waitRepairedCount, name: '无故障记录[车]' })
      this.dataRepaireTotalList.push({ value: result.data.repairCount, name: '有故障记录[车]' })
      this.dataRepaireTotalList.push({ value: this.waitRepairedCount, name: '无故障记录[车]' })
      this.dataRepaireTotalList.push({ value: this.totleCount, name: '合计' })
      this.loadPieChart('总车辆', 'repairedPieChart', dataRepaired, this.totleCount)
    })
    this.jsonApiService.http('deviceRepaired/countDataRecord.html', reqdata).subscribe(result => {
      this.dataAbnormalCarList = []
      this.dataAbnormalCarTotalList = []
      this.dataAbnormalCarTotal = 0
      if (result.data && result.success) {
        let temArr: any = result.data
        for (let key in temArr) {
          let obj = {
            value: temArr[key],
            name: key
          }
          this.dataAbnormalCarList.push(obj)
          this.dataAbnormalCarTotalList.push(obj)
          this.dataAbnormalCarTotal += temArr[key]
        }
        this.dataAbnormalCarTotalList.push({
          value: this.dataAbnormalCarTotal,
          name: '合计'
        })
        this.loadPieChart('问题总数', 'questionPieChart', this.dataAbnormalCarList, this.dataAbnormalCarTotal)
      }
    })
  }
  //饼状图,eleId:元素Id,data渲染的数据
  loadPieChart(name, eleId, data, total) {
    const questionPie = echarts.init(document.getElementById(eleId))
    questionPie.clear()
    const scale = 1
    let temArr = []
    for (let item of data) {
      if (item.value) {
        temArr.push(item)
      }
    }
    const echartData = temArr
    if (echartData.length == 0) {
      return
    }
    const rich = {
      yellow: {
        color: '#49dff0',
        fontSize: 18 * scale,
        padding: [5, 4],
        align: 'center'
      },
      total: {
        color: '#49dff0',
        fontSize: 28 * scale,
        align: 'center'
      },
      white: {
        color: '#fff',
        align: 'center',
        fontSize: 14 * scale,
        padding: [5, 4]
      },
      blue: {
        color: '#ffc72b',
        fontSize: 18 * scale,
        padding: [5, 4],
        align: 'center'
      },
      hr: {
        borderColor: '#0b5263',
        width: '100%',
        borderWidth: 1,
        height: 0
      }
    }
    var option = {
      backgroundColor: '#031f2d',
      title: {
        text: name,
        left: 'center',
        top: '53%',
        padding: [24, 0],
        textStyle: {
          color: '#fff',
          fontSize: 18 * scale,
          align: 'center'
        }
      },
      legend: {
        selectedMode: false,
        formatter: '{total|' + total + '}',
        data: [echartData[0].name],
        left: 'center',
        top: 'center',
        icon: 'none',
        align: 'center',
        textStyle: {
          color: '#fff',
          fontSize: 16 * scale,
          rich: rich
        }
      },
      series: [
        {
          name: name,
          type: 'pie',
          radius: ['42%', '50%'],
          hoverAnimation: false,
          color: [
            '#c23531',
            '#2f4554',
            '#61a0a8',
            '#d48265',
            '#91c7ae',
            '#749f83',
            '#ca8622',
            '#bda29a',
            '#6e7074',
            '#546570',
            '#c4ccd3'
          ],
          label: {
            normal: {
              formatter: function (params, ticket, callback) {
                return (
                  '{white|' +
                  params.name +
                  '}{yellow|' +
                  params.value +
                  '}\n{hr|}\n{blue|' +
                  ((+params.value / total) * 100).toFixed(1) +
                  '%}'
                )
              },
              rich: rich
            }
          },
          labelLine: {
            normal: {
              length: 35 * scale,
              length2: 0,
              lineStyle: {
                color: '#0b5263'
              }
            }
          },
          data: echartData
        }
      ]
    }
    questionPie.setOption(option)
    window.onresize = function () {
      if (questionPie) {
        questionPie.resize()
      }
    }
  }

  /**
   * 单行数据选中事件,仅支持单行选中,不支持多选
   */
  singleRowSelected(row, e, index) {
    if (
      e.target.className.includes('checkbox') ||
      e.target.className.includes('checkbox-flag') ||
      e.target.className.includes('checkbox-td') ||
      e.target.className.includes('checkbox-label')
    ) {
      this.rowSelected(row, e, index)
      return
    }
    for (let item of this.tableData) {
      item['isChecked'] = false
    }
    this.selected = []
    row.isChecked = !row.isChecked
    this.selected.push(row)
    this.rowId = row.id
  }
  //table 全部选中
  allSelected() {
    this.allChecked = !this.allChecked
    if (!this.allChecked) {
      for (let item of this.tableData) {
        item['isChecked'] = false
      }
      this.selected = []
      this.rowId = ''
    } else {
      var temArr = []
      for (let item of this.tableData) {
        item['isChecked'] = true
        temArr.push(item.id)
        this.selected.push(item)
      }
      for (let item of this.selected) {
        temArr.push(item.rowId)
      }
      this.rowId = temArr.join(',')
    }
  }

  //table复选框数据row选中事件回调:处理选中状态和deviceId
  rowSelected(row, e, index) {
    var index = $.inArray(row, this.selected)
    if (index === -1) {
      row.isChecked = true
      this.selected.push(row)
    } else {
      row.isChecked = false
      this.selected.splice(index, 1)
    }
    var temArr = []
    for (let item of this.selected) {
      temArr.push(item.id)
    }
    this.rowId = temArr.join(',') //处理deviceId,与后台接口交互参数
    this.selected.length === this.pageSize ? (this.allChecked = true) : (this.allChecked = false) //判断是否全选状态
  }

  // 限制进厂标志 1 批量限制进场 2 折线图中的单独限制进场操作
  limitPushFlag = 1

  //批量进厂限制
  updata_device(modal) {
    this.limitPushFlag = 1
    if (this.rowId == '' || this.selected.length == 0) {
      this.jsonApiService.message('请勾选至少一条数据')
      return
    }
    modal.show()
  }

  singleLimitPush(modal) {
    this.limitPushFlag = 2
    modal.show()
  }

  //确定批量进厂限制
  autoReset(modal) {
    let isPush = this.lgisPush == 'time' ? '0' : this.lgisPush
    let isPushTime = this.lgisPush == 'time' ? this.isPushTime : ''

    const ids = this.limitPushFlag === 1 ? this.rowId : this.selectedRow.id
    let reqdata = {
      ids,
      isPush: isPush,
      time: isPushTime
    }
    //		'ids=' + this.rowId + "&isPush=" + this.lgisPush;
    this.jsonApiService.http_obj('deviceRepaired/enterFactoryLimitBatch.html', reqdata).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        modal.hide()
        this.lgisPush = '0'
        this.isPushTime = 6
        this.refresh()
        this.selected = []
        this.rowId = ''
        if (this.limitPushFlag === 2) {
          this.selectedRow.isPush = Number(isPush)
          this.lineParamDeal(this.selectedRow)
          return
        }
      }
    })
  }
  // 取消限制
  cancelRestrict(row) {
    this.jsonApiService.confirm_message('确定要取消自定义限制[' + row.restrictTime + '后限制]?').then(() => {
      let reqdata = 'id=' + row.id
      this.jsonApiService.http('deviceRepaired/removeRestrictions.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.refresh()
        }
      })
    })
  }
  //取消批量进厂限制
  lgModalhide(modal) {
    modal.hide()
    this.lgisPush = '0'
    this.isPushTime = 6
    // 折线图中操作
    if (this.limitPushFlag === 2) return
    this.rowId = ''
    this.selected = []
    for (let item of this.tableData) {
      item['isChecked'] = false
    }
  }
  //自定义限制,校验非空值,默认6小时,不允许为空
  inputChange() {
    this.isPushTime = Math.abs(Math.floor(this.isPushTime))
    if (!this.isPushTime) {
      this.isPushTime = 6
    }
  }
  //批量进厂限制选框change事件
  resetChange(checked, type) {
    //		if(type === 'Y'&&checked){
    //			this.lgisPush = 1;
    //		}else if(type === 'N'&&checked){
    //			this.lgisPush = 0;
    //		}
  }
  /**
   * 设置厂区在线
   */
  // 点击弹出设置厂区在线的弹框
  setFactoryOnline(modal) {
    this.factoryOnlineSearchKey = ''
    //这里还要做加载表单
    this.loadFactoryOnline()
    this.initAllProjectName().then(() => {
      this.selectCompanyName()
    })
    modal.show()
  }
  // 进厂限制设置表单刷新
  factoryTableRefresh() {
    this.loadFactoryOnline()
  }
  //分页回调
  factoryPaginate(e) {
    this.factoryOnlineCurPage = e.page + 1
    this.factoryOnlinePageSize = e.rows
    this.loadFactoryOnline()
  }
  comptyNameList: any
  //擦除用户所选项目名称
  delfactorySetCompany() {
    this.onlineSetCompanyId = ''
    this.onlineSetCompanyName = ''
    //采用简单粗暴的方法清除;官方推荐的方法失效
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#factorySetCompanyId').val('')
    $('#select2-factorySetCompanyId-container').empty()
    $('#select2-factorySetCompanyId-container').attr('title', '')
    $('#select2-factorySetCompanyId-container').prepend(str)
  }
  //初始化项目名称select2 选项
  selectCompanyName() {
    var that = this

    $('#factorySetCompanyId')
      .select2({
        language: 'zh-CN',
        placeholder: '请选择',
        allowClear: true,
        data: this.comptyNameList //为Select添加数据
      })
      .on('select2:select', function (e) {
        var data = e.params.data
        that.onlineSetCompanyName = data.text
        that.onlineSetCompanyId = data.id
      })
  }
  //拉取项目名称
  initAllProjectName() {
    var that = this
    return new Promise(function (resolve, reject) {
      that.jsonApiService.http('project/projectList.html', null).subscribe(data => {
        if (data.success) {
          var userList = data.data
          var selectdata = []
          for (var i = 0; i < userList.length; i++) {
            var obj = {
              id: userList[i].id,
              text: userList[i].projectName
            }
            selectdata[i] = obj
          }
        }
        that.comptyNameList = selectdata
        resolve()
      })
    })
  }
  // 设置厂区在线的公司选择回调
  onlinecompanySelected(data) {
    // 请求验证接口
    this.onlineSetCompanyId = data.companyId
    this.onlineSetCompanyName = data.companyName
  }
  // 搜索进厂限制设置
  factoryOnlineSearch() {
    this.factoryOnlineCurPage = 1
    this.loadFactoryOnline()
  }
  // 加载进厂限制设置表数据
  loadFactoryOnline() {
    let param = {
      pageSize: this.factoryOnlinePageSize,
      nowPage: this.factoryOnlineCurPage,
      parameters: {
        companyId: this.onlineSetCompanyId, // 公司id
        searchKey: this.factoryOnlineSearchKey
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(param)
    this.jsonApiService.http('factoryLimit/list.html', reqdata).subscribe(data => {
      for (let i = 0; i < data.exhibitDatas.length; i++) {
        let periodTime = data.exhibitDatas[i].period
        let endTime = parseInt(periodTime[periodTime.length - 1]) + 1
        data.exhibitDatas[i].periodTime = periodTime[0] + '点-' + endTime + '点'
      }
      this.factoryOnlineTableData = data.exhibitDatas
      this.factoryOnlinetotalCount = data.recordCount
    })
  }
  // 进厂限制设置关键字搜索
  factory_table_search() {
    this.factoryOnlineCurPage = 1
    this.factoryOnlineSearchKey = common.stringTrim(this.factoryOnlineSearchKey)
    this.loadFactoryOnline()
  }

  // 添加厂区的实体对象
  factory: any = {
    companyId: '', //公司id
    companyName: '', //公司名称
    period: '',
    isRepaired: 1,
    isAlarm: 1
  }
  // 添加厂区弹窗
  factoryAdd(modal, type) {
    this.fromType = type
    this.factory = {
      companyId: '', //公司id
      companyName: '', //公司名称
      period: '',
      isRepaired: 1,
      isAlarm: 1
    }
    this.selfTimeInputId = ''
    $('#setFactoryFrom').data('bootstrapValidator').resetForm()
    modal.show()
  }
  // 编辑厂区弹窗
  editFactory(row, modal, type) {
    this.fromType = type
    this.factory = JSON.parse(JSON.stringify(row))
    this.selfTimeInputId = row.periodTime
    modal.show()
  }
  // 公司选中回调
  factorySelected(data) {
    if (data.companyId) {
      if (this.fromType == 'update' && this.factory.companyId != data.companyId) {
        this.checkFactory(data.companyId)
      }
      if (this.fromType == 'new') {
        this.checkFactory(data.companyId)
      }
      this.factory.companyId = data.companyId
      this.factory.companyName = data.companyName
      $('#selectCompanyName').val(this.factory.companyId)
    }
  }
  onclickSelectCompany() {
    $('#s_timePicker').attr('class', 's_timePicker')
  }
  // 关闭弹框
  closeFactory(modal) {
    $('#setFactoryFrom').data('bootstrapValidator').resetForm()
    this.selfTimeInputId = ''
    $('#s_timePicker').attr('class', 's_timePicker')
    modal.hide()
  }
  // 删除厂区
  delFactory(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除').then(() => {
      let reqdata = 'id=' + row.id
      this.jsonApiService.http('factoryLimit/delete.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.loadFactoryOnline()
        }
      })
    })
  }
  // 校验厂区
  checkFactory(data) {
    let reqdata = 'companyId=' + data
    this.jsonApiService.http('factoryLimit/validateCompanyId.html', reqdata).subscribe(data => {
      if (data.message.indexOf('此厂区限制已存在') != -1) {
        this.jsonApiService.message(data.message)
        this.factory.companyName = ''
        this.factory.companyId = ''
        $("input[name='companyName']").val('').change()
      }
    })
  }
  // 添加提交
  addSubmitFactory(modal) {
    $('#setFactoryFrom').bootstrapValidator('validate') //开启验证
    let isValid = $('#setFactoryFrom').data('bootstrapValidator').isValid() //验证是否通过

    if (isValid) {
      this.jsonApiService.http_obj('factoryLimit/add.html', this.factory).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.loadFactoryOnline()
          this.closeFactory(modal)
        }
      })
    }
  }
  // 编辑提交
  editSubmitFactory(modal) {
    $('#setFactoryFrom').bootstrapValidator('validate') //开启验证
    let isValid = $('#setFactoryFrom').data('bootstrapValidator').isValid() //验证是否通过
    if (isValid) {
      this.jsonApiService.http_obj('factoryLimit/update.html', this.factory).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          //
          this.loadFactoryOnline()
          this.closeFactory(modal)
        }
      })
    }
  }
  //自定义时间input点击时间回调
  isShowTimer() {
    $('.s_timePicker').toggleClass('s_isActive')
    this.startTimeSelected = null
    this.endTimeSelected = null
  }
  //自定义时间段校验
  validTime(str1, str2) {
    this.selfTimeData = []
    this.factory.period = []
    var hourListLen = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
    //对渲染的数据进行整合,提起始时间和结束时间
    if (str1 == str2) {
      if (str1 === 0) {
        this.selfTimeData = hourListLen.slice(str1, hourListLen.length - 1)
      } else {
        var selfTimeData1 = hourListLen.slice(str1, hourListLen.length)
        var selfTimeData2 = hourListLen.slice(0, str1)
        this.selfTimeData = selfTimeData1.concat(selfTimeData2)
      }
    }
    if (str1 > str2) {
      var selfTimeData3 = hourListLen.slice(str1, hourListLen.length)
      var selfTimeData4 = hourListLen.slice(0, str2)
      this.selfTimeData = selfTimeData3.concat(selfTimeData4)
    }
    if (str1 < str2) {
      this.selfTimeData = hourListLen.slice(str1, str2)
    }

    this.factory.period = this.selfTimeData
  }
  //提交自定义时间picker
  submitTimerSelected() {
    if (this.startTimeSelected === 0 || this.endTimeSelected === 0) {
    } else {
      if (!this.startTimeSelected) {
        this.jsonApiService.message('请选择开始时间')
        return
      } else if (!this.endTimeSelected) {
        this.jsonApiService.message('请选择结束时间')
        return
      }
    }
    this.selfTimeInputId = this.startTimeSelected + '点-' + this.endTimeSelected + '点'
    $('#selfTimeInput').val(this.selfTimeInputId).change()
    $('.s_timePicker').toggleClass('s_isActive')
    this.validTime(this.startTimeSelected, this.endTimeSelected)
  }
  //时间段选定值点击事件回调
  selectedTime(val, type) {
    if (type === 'start') {
      this.startTimeSelected = val
    } else if (type === 'end') {
      this.endTimeSelected = val
    }
  }
  //维修记录
  clickRecord(type) {
    this.factory.isRepaired = type
  }
  //设备警告
  clickWarning(type) {
    this.factory.isAlarm = type
  }
  //删除时间段
  delSelfTime() {
    this.selfTimeInputId = ''
    $('#selfTimeInput').val('').change()
  }

  /**
   *
   *
   * 表头管理
   *
   *
   *
   */
  faultJson: any = [
    {
      field: '勾选',
      fieldName: 'isChecked',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 1
    },
    {
      field: '操作',
      fieldName: 'operation',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 2
    },
    {
      field: '维修前图片',
      fieldName: 'beforeImageInfo',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 3
    },
    {
      field: '维修后图片',
      fieldName: 'afterImageInfo',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 4
    },
    {
      field: '车牌号码',
      fieldName: 'carNumber',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 5
    },
    {
      field: '所属公司',
      fieldName: 'companyName',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 6
    },
    {
      field: '故障类型',
      fieldName: 'faultTypeName',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 7
    },
    {
      field: '维修人员',
      fieldName: 'repairedUser',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 8
    },
    {
      field: '维修时间',
      fieldName: 'repairedTime',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 9
    },
    {
      field: '响应时长',
      fieldName: 'responseTime',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 10
    },
    {
      field: '故障现象',
      fieldName: 'faultPhenomenon',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 11
    },
    {
      field: '维修记录',
      fieldName: 'repairedRecords',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 12
    },
    {
      field: '维修总结',
      fieldName: 'repairedConclusion',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 13
    },
    {
      field: 'GPS天线',
      fieldName: 'gpsAntenna',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 14
    },
    {
      field: 'GSM天线',
      fieldName: 'gsmAntenna',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 15
    },
    {
      field: '维修订单状态',
      fieldName: 'payStatus',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 16
    },
    {
      field: '进厂限制',
      fieldName: 'isPush',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 17
    },
    {
      field: '备注',
      fieldName: 'remark',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 18
    },
    {
      field: '故障状态',
      fieldName: 'repairedStatus',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 19
    },
    {
      field: '故障时间',
      fieldName: 'faultTime',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 20
    },
    {
      field: '录入人员',
      fieldName: 'creater',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 21
    },
    {
      field: '录入时间',
      fieldName: 'createTime',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 22
    },
    {
      field: '最后编辑',
      fieldName: 'lastUpdateTime',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 23
    },
    {
      field: '司机电话',
      fieldName: 'driverPhone',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 24
    },
    {
      field: '最后拨打人',
      fieldName: 'callUser',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 25
    },
    {
      field: '最后拨打时间',
      fieldName: 'callTime',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 26
    },
    {
      field: '最后通话时长',
      fieldName: 'callDuration',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 27
    },
    {
      field: '最后联系结果',
      fieldName: 'contactResult',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 28
    },
    {
      field: '联系记录',
      fieldName: 'callRecord',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 29
    },
    {
      field: '设备ID',
      fieldName: 'deviceId',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 30
    },
    {
      field: '故障来源',
      fieldName: 'updateSource',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 31
    },
    {
      field: '维修指导',
      fieldName: 'repairedGuide',
      mark: 'device-management:fault',
      menuName: '设备故障记录',
      isHide: 0,
      order: 32
    }
  ]
  isSwitch: boolean = false //默认隐藏
  faultList: any = [] //页面jsonList
  faultPopupList: any = [] //弹窗jsonList
  //插入数据库表头
  insertHeader() {
    this.jsonApiService
      .http_obj('header/insertBatchHeader.html', { headerEntityList: JSON.stringify(this.faultJson) })
      .subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.reaustHeader() //再次请求表头
        }
      })
  }
  //请求表头
  reaustHeader() {
    this.jsonApiService.http_obj('header/field.html', { mark: 'device-management:fault' }).subscribe(data => {
      if (!data.success) {
        this.insertHeader()
      } else {
        var dataList = data.data.headerList

        for (let i = 0; i < dataList.length; i++) {
          if (dataList[i].isHide == 0) {
            dataList[i].isStatus = true
          } else {
            dataList[i].isStatus = false
          }
          dataList[i].order = i + 1
        }
        this.faultList = JSON.parse(JSON.stringify(dataList))
        this.faultPopupList = JSON.parse(JSON.stringify(dataList))
      }
    })
  }
  //初始化开关
  initSwitch() {
    var that = this
    $('.isStatus').bootstrapSwitch({
      //初始化按钮
      onText: '显示',
      offText: '隐藏',
      onColor: 'primary',
      offColor: 'warning',
      onSwitchChange: function (event, state) {
        // state 为true 隐藏  false 不隐藏
        if (state == true) {
          that.checkStatus(0, event.target.attributes.key.nodeValue)
        } else {
          that.checkStatus(1, event.target.attributes.key.nodeValue)
        }
      }
    })
  }
  setHeader(modal) {
    var that = this
    this.faultPopupList = JSON.parse(JSON.stringify(this.faultList))
    modal.show()
    System.import('assets/js/bootstrap-switch.min.js').then(() => {
      System.import('assets/css/bootstrap-switch.min.css').then(() => {
        setTimeout(function () {
          that.initSwitch()
          that.isSwitch = true
        }, 1)
      })
    })
  }
  //关闭表头弹窗
  closeHeader(modal) {
    modal.hide()
    this.isSwitch = false
  }
  //重置表头
  recoveryHeader() {
    var that = this

    this.faultPopupList = JSON.parse(JSON.stringify(this.faultList))

    System.import('assets/js/bootstrap-switch.min.js').then(() => {
      System.import('assets/css/bootstrap-switch.min.css').then(() => {
        setTimeout(function () {
          that.initSwitch()
          that.isSwitch = true
        }, 1)
      })
    })
  }
  //确定提交表头
  submitHeader(modal) {
    var mark = 'device-management:fault'
    var field = []
    var fieldName = []
    var isShow = []
    for (var i = 0; i < this.faultPopupList.length; i++) {
      field.push(this.faultPopupList[i].field)
      fieldName.push(this.faultPopupList[i].fieldName)
      isShow.push(this.faultPopupList[i].isHide)
    }
    var reqdata = new FormData()

    reqdata.append('mark', mark)
    reqdata.append('field', field.join(','))
    reqdata.append('fieldName', fieldName.join(',')) //type 1获取相对路径  2获取绝对路径
    reqdata.append('isShow', isShow.join(','))

    this.jsonApiService.form_http('header/updateBatchHeader.html', reqdata).subscribe(data => {
      if (data.success) {
        modal.hide()
        this.isSwitch = false
        this.reaustHeader() //请求表头
        this.load()
      }
    })
  }
  //移动 type 1:上移  2：下移  3：置顶  4：置底
  MoveClick(row, type) {
    var that = this
    if (row.order == 1) {
      if (type == '1') {
        this.jsonApiService.message('已经在第一位，暂不能上移')
        return
      } else if (type == '3') {
        this.jsonApiService.message('已经在第一位，暂不能置顶')
        return
      }
    }

    if (row.order == this.faultPopupList.length) {
      if (type == '2') {
        this.jsonApiService.message('已经在最后一位，暂不能下移')
        return
      } else if (type == '4') {
        this.jsonApiService.message('已经在最后一位，暂不能置底')
        return
      }
    }

    var List = JSON.parse(JSON.stringify(this.faultPopupList))
    for (var i = 0; i < List.length; i++) {
      if (List[i].order == row.order) {
        if (type == '1') {
          List[i - 1].order = List[i - 1].order + 1
          List[i].order = row.order - 1
          break
        } else if (type == '2') {
          List[i + 1].order = List[i + 1].order - 1
          List[i].order = row.order + 1
          break
        } else if (type == '3') {
          List[i].order = 1
        } else if (type == '4') {
          List[i].order = List.length
        }
      } else {
        if (List[i].order > row.order && type == '4') {
          List[i].order = List[i].order - 1
        } else if (List[i].order < row.order && type == '3') {
          List[i].order = List[i].order + 1
        }
      }
    }

    List = List.sort(this.compare('order'))
    this.faultPopupList = JSON.parse(JSON.stringify(List))

    System.import('assets/js/bootstrap-switch.min.js').then(() => {
      System.import('assets/css/bootstrap-switch.min.css').then(() => {
        setTimeout(function () {
          that.initSwitch()
          that.isSwitch = true
        }, 1)
      })
    })
  }
  compare(property) {
    return function (a, b) {
      var value1 = a[property]
      var value2 = b[property]
      return value1 - value2
    }
  }

  //是否启用
  checkStatus(check, key) {
    var that = this
    var List = JSON.parse(JSON.stringify(this.faultPopupList))
    for (var i = 0; i < List.length; i++) {
      if (List[i].fieldName == key) {
        if (check == '0') {
          List[i].isHide = check
          List[i].isStatus = true
        } else {
          List[i].isHide = check
          List[i].isStatus = false
        }
      }
    }

    List = List.sort(this.compare('order'))
    this.faultPopupList = JSON.parse(JSON.stringify(List))

    System.import('assets/js/bootstrap-switch.min.js').then(() => {
      System.import('assets/css/bootstrap-switch.min.css').then(() => {
        setTimeout(function () {
          that.initSwitch()
          that.isSwitch = true
        }, 1)
      })
    })
  }

  /* 新增

    不良记录

  */
  //新增 操作
  recordDetailFrom: any = {
    id: '',
    returnTime: '',
    carNumber: '',
    companyName: '',
    deviceId: '',
    productNo: '',
    productTime: '',
    hwVersion: '',
    retestResult: '',
    badReasons: '',
    improvementStrategy: '',
    resolutionTime: '',
    principal: '',
    imagePaths: '',
    faultPhenomenon: '',
    repairedId: '',
    relation: 0,
    repairSubdivideStr: ''
  }
  imageInfoList: any = []
  addRecordDetail(modal) {
    for (let key in this.recordDetailFrom) {
      this.recordDetailFrom[key] = ''
    }
    this.imageInfoList = []
    this.recordDetailFrom.relation = 0 //默认是未关联
    this.recordDetailFrom.returnTime = common.getTimeMmss(new Date())
    if (this.selected.length == 0) {
      this.jsonApiService.message('请先选择一条记录来新增')
      return
    }
    if (this.selected.length != 1) {
      this.jsonApiService.message('只能选择一条[已维修]记录来新增')
      return
    }
    if (this.selected[0].repairedStatus != 1) {
      this.jsonApiService.message('只能选择一条[已维修]记录来新增')
      return
    }
    this.recordDetailFrom.carNumber = this.selected[0].carNumber
    this.recordDetailFrom.deviceId = this.selected[0].deviceId
    this.recordDetailFrom.companyName = this.selected[0].companyName
    this.recordDetailFrom.faultPhenomenon = this.selected[0].faultPhenomenon
    this.recordDetailFrom.repairedId = this.selected[0].id
    this.recordDetailFrom.relation = this.selected[0].id ? 1 : 0 //0 未关联 1已关联
    this.recordDetailFrom.repairSubdivideStr = this.selected[0].repairedRecords.join(',')
    this.jsonApiService
      .http_obj('deviceRepaired/getDeviceBaseDataV2.html', {
        deviceId: this.selected[0].deviceId,
        repairedTime: this.selected[0].repairedTime ? this.selected[0].repairedTime : ''
      })
      .subscribe(data => {
        if (data.success) {
          this.recordDetailFrom.productNo = data.data.productNo ? data.data.productNo : ''
          this.recordDetailFrom.productTime = data.data.productTime ? data.data.productTime : ''
          this.recordDetailFrom.hwVersion = data.data.hwVersion ? data.data.hwVersion : ''
          modal.show()
        } else {
          this.jsonApiService.message(data.message)
        }
      })
  }
  recordDetailClose(modal) {
    for (let key in this.recordDetailFrom) {
      this.recordDetailFrom[key] = ''
    }
    modal.hide()
  }
  recordDetailSubmit(modal) {
    if (!this.recordDetailFrom.returnTime) {
      this.jsonApiService.message('寄回时间不能为空')
      return
    }
    if (!this.recordDetailFrom.deviceId) {
      this.jsonApiService.message('设备ID不能为空')
      return
    }
    if (!this.recordDetailFrom.faultPhenomenon) {
      this.jsonApiService.message('故障现象不能为空')
      return
    }
    this.recordDetailFrom.imagePaths = this.imageInfoList.join(',')
    let reqdata = JSON.parse(JSON.stringify(this.recordDetailFrom))
    this.jsonApiService.http_obj('deviceRepaired/add.html', reqdata).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        this.load()
        modal.hide()
      }
    })
  }

  fileList: File = null
  //上传多张
  multifileChange(files: FileList) {
    if (this.isViewer2 && $('.viewer-container').length > 0) {
      this.viewer.destroy()
    }

    var that = this
    let multfileList = files

    var reqdata = new FormData()
    reqdata.append('describe', '不良记录')
    reqdata.append('businessType', '1')
    // reqdata.append('deviceId', this.page.deviceId);
    reqdata.append('type', '2') //type 1获取相对路径  2获取绝对路径

    for (var i = 0; i < multfileList.length; i++) {
      this.fileList = multfileList[i]
      const isJPG =
        this.fileList.type === 'image/jpeg' || this.fileList.type === 'image/jpg' || this.fileList.type === 'image/png'
      if (!isJPG) {
        this.jsonApiService.message('上传图片只能是 png, jpg, jpeg 格式!')
        return
      }

      reqdata.append('files', multfileList[i])
    }

    that.jsonApiService.form_http('fileUpload/upload.html', reqdata).subscribe(data => {
      if (data.success) {
        for (var i = 0; i < data.data.length; i++) {
          that.imageInfoList.push(data.data[i])
        }
      }
    })

    for (let k = 0; k < $('.up').length; k++) {
      $('.up')[k].value = null
    }
  }
  //删除
  deleteImg(i) {
    this.imageInfoList.splice(i, 1)

    if (this.isViewer2 && $('.viewer-container').length > 0) {
      this.viewer.destroy()
    }
  }
  bigImg2: any = '' //
  isViewer2: boolean = false //默认隐藏
  bigImgClick(modal, img) {
    // modal.show();
    this.bigImg2 = img
    if (this.isViewer2 && $('.viewer-container').length > 0) {
      System.import('assets/js/viewer/viewer.js').then(() => {
        System.import('assets/js/viewer/bootstrap.bundle.min.js').then(() => {
          System.import('assets/js/viewer/viewer.css').then(() => {
            this.showImg2()
          })
        })
      })
    } else {
      this.showImg2()
    }
  }
  //显示图片组件
  viewer2: any = ''
  showImg2() {
    var that = this
    var imgList = $('.imgFileList')[0]
    this.viewer2 = new Viewer(imgList, {
      url: 'src',
      title: function (image) {
        return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')'
      }
    })
    that.isViewer2 = true
  }

  // 通话详情记录
  callRecordDetailList: any = []
  callRecordPageSize: number = 10
  callRecordCurPage: number = 1
  callRecordTotalCount: number = 0
  callRecordActiveId: string = ''
  callRecordDetail(row, modal) {
    this.callRecordActiveId = row.id
    modal.show()
    this.loadCallRecord()
  }
  // 通话详情记录分页
  loadCallRecord() {
    let data = {
      pageSize: this.callRecordPageSize,
      nowPage: this.callRecordCurPage,
      parameters: {
        id: this.callRecordActiveId
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('deviceRepairedV2/getContactListById.html', reqdata).subscribe(result => {
      if (result.isSuccess) {
        this.callRecordDetailList = []
        this.callRecordDetailList = result.exhibitDatas
        this.callRecordTotalCount = result.recordCount
        this.callRecordDetailList.map(item => (item.callDuration = common.secondToDate(item.callDuration)))
      }
    })
  }
  //分页回调
  callRecordPaginate(e) {
    this.callRecordCurPage = e.page + 1
    this.callRecordPageSize = e.rows
    this.loadCallRecord()
  }

  /**
   * 导入
   */
  fileUp: string = ''
  fileToUpload: File = null //上传文件回调参数
  // 显示导入的弹框
  showImportModal(modal) {
    modal.show()
  }
  // 关闭导入的弹框
  cancelUp(val) {
    val.hide()
    this.fileToUpload = null
  }
  //下载模板
  load_module() {
    var elemIF = document.createElement('iframe')
    elemIF.src = config.BaseURL + 'resources/template/materiel-Template.xlsx'
    elemIF.style.display = 'none'
    document.body.appendChild(elemIF)
  }
  // 清空input type=file输入框的值
  clearFile() {
    this.fileUp = ''
  }
  //文件上传change回调
  fileChange(files: FileList) {
    this.fileToUpload = files.item(0)
    const isEXCEL =
      this.fileToUpload.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
      this.fileToUpload.type === 'application/vnd.ms-excel'
    if (!isEXCEL) {
      this.jsonApiService.message('上传文件只能是 excel格式!')
      this.fileToUpload = null
      return
    }
  }
  //导入submit
  submitData(val) {
    let postParam = new FormData()
    postParam.append('file', this.fileToUpload)
    if (!this.fileToUpload) {
      this.jsonApiService.message('请上传文件')
      return false
    }
    this.jsonApiService.form_http('deviceRepaired/uploadCarExcel.html', postParam).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        val.hide()
        this.fileToUpload = null
        this.load()
      }
    })
  }

  /**
   * 查看车辆离线地点
   */
  map = null
  ids = ''
  // 显示导入的弹框
  showCarOfflineModal(modal) {
    if (this.rowId) {
      modal.show()
      this.initMap()
      this.initCarList()
    } else {
      this.jsonApiService.message('请勾选至少一条数据')
    }
  }

  initMap() {
    this.map = new BMap.Map('allmap', { enableMapClick: false }) //我的地图
    this.map.centerAndZoom(new BMap.Point(115.9, 40.2), 11) // 初始化地图,设置中心点坐标和地图级别
    this.map.enableScrollWheelZoom(true) //开启鼠标滚轮缩放
  }

  //初始化车辆离线地点
  initCarList() {
    let pointsView = []
    let reqdata = 'ids=' + this.rowId
    this.jsonApiService.http('deviceRepaired/getLatLngMsg.html', reqdata).subscribe(result => {
      const data = result.data
      if (data && data.length > 0) {
        const pointIcon = new BMap.Icon('assets/img/trackImage/point.png', new BMap.Size(20, 30))
        for (let i = 0; i < data.length; i++) {
          const item = data[i]
          const point = new BMap.Point(item.offlineLng, item.offlineLat)
          const content =
            '<div class="mInfoul"><ul>' +
            '<li style="color:#fff">' +
            item.carNumber +
            '<li>' +
            '<li style="margin-top:7px">离线时间：' +
            item.offlineDate +
            '<li>' +
            '</ul></div>'
          let marker = new BMap.Marker(point, { icon: pointIcon }) // 创建标注

          const infoWindow = new BMap.InfoWindow(content)
          const that = this
          marker.addEventListener('mouseover', function (e) {
            that.map.openInfoWindow(infoWindow, e.point) //开启信息窗口openInfoWindow(infoWindow)
            $('.BMap_pop>img').hide()
          })
          marker.addEventListener('mouseout', function (e) {
            that.map.closeInfoWindow(infoWindow, e.point)
          })

          this.map.addOverlay(marker)
          pointsView.push(point)
        }
        let timer = setTimeout(() => {
          this.map.setViewport(pointsView)
          const viewport = this.map.getViewport(pointsView)
          if (viewport.zoom > 14) {
            this.map.setZoom(14)
          }
          clearTimeout(timer)
          timer = null
        }, 200)
      } else {
        this.jsonApiService.message('没有离线坐标！')
      }
    })
  }
  // 关闭导入的弹框
  cancelCarOfflineModal(val) {
    this.map = null
    val.hide()
  }

  //设备基本信息
  getDeviceBasicInfo() {
    this.jsonApiService
      .http_obj('system/getDeviceBaseInfoByDeviceId.html', {
        deviceId: this.selectedRow.deviceId,
        factoryId: this.selectedRow.companyId
      })
      .subscribe(result => {
        this.haveRepaireObj = result.data.haveRepaired
        if (result.repaired) {
          this.selectedRow.isPush = result.repaired.isPush
        }
        this.echartLimitTitle = this.selectedRow.isPush === 0 ? '限制进厂' : '已限制'

        //编辑设备信息 回显标记设备状态的标记 gps问题和编辑表单
        this.getEditDeviceInfo()
        this.haveRepaireObj = result.data.haveRepaired
        // 添加设备状态中的传感器的数据
        if (result.data.sensorChannel && result.data.sensorChannel.length > 0) {
          let temArr: any = []
          for (var j = 0; j < result.data.sensorChannel.length; j++) {
            let obj = {
              value: result.data.sensorChannel[j],
              flag: false,
              isFront: '0'
            }
            if (result.data.coef) {
              if (result.data.coef[+result.data.sensorChannel[j] - 1]) {
                obj.flag = true
              }
            }
            if (result.data.sensorAxle && result.data.sensorAxle.length > 0) {
              obj.isFront = result.data.sensorAxle[j]
            }
            //					if(result.data.sensorAxle.length == result.data.sensorChannel.length){
            //						obj.isFront= result.data.sensorAxle[j]
            //					}
            temArr.push(obj)
          }
          result.data.sensorChannel = temArr
          this.loadSensorModule(result.data.sensorChannel)
        } else {
          this.loadSensorModule([])
        }
        this.deviceOffline.selected = false
        this.deviceContact.selected = false
        this.deviceRepairedIspush.selected = false
      })
  }

  // 标记设备状态打开的弹框的一些参数

  sensorSelectAll: any = {
    faultTypeName: '传感器问题',
    programType: '202',
    text: '传感器问题',
    selected: false
  }

  // 传感器的渲染数组
  sensorModuleList: any = []

  updateSensorProblem(item) {
    let sensorProblem: string = ''
    for (let lis of item.child) {
      if (lis.selected) {
        sensorProblem = item.text + '-' + lis.text
      }
    }
    if (!sensorProblem) {
      this.jsonApiService.message('请选择传感器问题')
      return
    }
    let reqdata = {
      deviceId: this.selectedRow.deviceId,
      index: item.value - 1,
      startTime: $('#datetimepicker3').val(),
      endTime: $('#datetimepicker4').val(),
      sensorProblem: sensorProblem
    }
    this.jsonApiService.http_obj('car/updateSensorProblem.html', reqdata).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        this.getEditDeviceInfo()
      }
    })
  }

  // 标记设备状态打开的弹框
  sensorSelectAllClick() {
    this.sensorSelectAll.selected = !this.sensorSelectAll.selected
  }

  // 传感器选择的
  sensorLisSelected(id, code) {
    for (let item of this.sensorModuleList) {
      if (item.value == id) {
        for (let lis of item.child) {
          if (lis.code == code) {
            lis.selected = !lis.selected
          } else {
            lis.selected = false
          }
        }
      }
    }
    this.sensorSelectAll.selected = false
    for (let item of this.sensorModuleList) {
      for (let lis of item.child) {
        if (lis.selected) {
          this.sensorSelectAll.selected = true
          break
        }
      }
    }
  }

  // 问题区间数据查看,查看问题区间重量曲线图
  dataDrawEchartBMap(item) {
    let queryParams = {
      deviceId: this.selectedRow.deviceId,
      carNumber: this.selectedRow.carNumber,
      startDate: item.startTime_chart,
      endDate: item.endTime_chart
    }
    let BaseURL = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port
    common.setCookie('jumpFromOrderManagenment', JSON.stringify(queryParams))
    window.open(BaseURL + '#/system-config/data-optimization')
  }
  // 传感器全部平直,更新至车辆管理表
  isAllStraight: boolean = false

  page: any = {
    id: '',
    companyId: '',
    carNumber: '',
    deviceId: '',
    useTypeL1: '',
    useTypeL2: '',
    sensorType: '2',
    sensorAmount: '',
    sensorChannel: [],
    carAxleAmount: '',
    gpsAntenna: '',
    gsmAntenna: '',
    phone: '',
    driverName: '',
    sensorAxle: [], //传感器通道
    sensorPosition: [] //安装位置
  }

  inputParam: any = []

  deviceSensorArr: any = [
    { id: 1, text: '通道1', checked: false },
    { id: 2, text: '通道2', checked: false },
    { id: 3, text: '通道3', checked: false },
    { id: 4, text: '通道4', checked: false },
    { id: 5, text: '通道5', checked: false },
    { id: 6, text: '通道6', checked: false },
    { id: 7, text: '通道7', checked: false },
    { id: 8, text: '通道8', checked: false },
    { id: 9, text: '通道9', checked: false },
    { id: 10, text: '通道10', checked: false },
    { id: 11, text: '通道11', checked: false },
    { id: 12, text: '通道12', checked: false },
    { id: 13, text: '通道13', checked: false },
    { id: 14, text: '通道14', checked: false },
    { id: 15, text: '通道15', checked: false },
    { id: 16, text: '通道16', checked: false }
  ]

  ChannelLen: any = '' //原始轴的个数
  installArray: any = [] //安装位置
  sensorAxleFront: any = [] //通道前
  sensorAxleAfter: any = [] //通道后

  checkChannel: any = [] //选中通道数组

  haveRepaireObj: any = {} // 已维修返回的对象  system/getDeviceBaseInfoByDeviceId.html这个接口请求后存在对象中方便不同的方法使用这个对象

  GPSProblemList = {
    startTime: '',
    endTime: '',
    operator: '',
    operatingTime: '',
    gpsProblem: '',
    selected: false
  }

  GPSSelectAll: any = {
    faultTypeName: 'GPS问题',
    programType: '203',
    text: 'GPS问题',
    selected: false
  }
  GPSModuleList: any = [
    {
      faultTypeName: 'GPS问题',
      programType: '203',
      text: '无GPS',
      code: 'GP1',
      selected: false
    },
    {
      faultTypeName: 'GPS问题',
      programType: '203',
      text: '停车速度平直',
      code: 'GP2',
      selected: false
    },
    {
      faultTypeName: 'GPS问题',
      programType: '203',
      text: '大段丢失',
      code: 'GP3',
      selected: false
    },
    {
      faultTypeName: 'GPS问题',
      programType: '203',
      text: '偶尔丢失',
      code: 'GP4',
      selected: false
    }
  ]
  algorithmQuestionList: any = [
    {
      exceptionType: '1',
      programType: '101',
      faultTypeName: '算法问题',
      text: '上货问题',
      selected: false
    },
    {
      exceptionType: '1',
      programType: '104',
      faultTypeName: '算法问题',
      text: '多次上货',
      selected: false
    },
    {
      exceptionType: '1',
      programType: '102',
      faultTypeName: '算法问题',
      text: '卸货问题',
      selected: false
    },
    {
      exceptionType: '1',
      programType: '105',
      faultTypeName: '算法问题',
      text: '多次卸货',
      selected: false
    },
    {
      exceptionType: '1',
      programType: '103',
      faultTypeName: '算法问题',
      text: '在途问题',
      selected: false
    }
  ]

  // 接电问题
  deviceContact: any = {
    faultTypeName: '主机问题',
    programType: '201',
    text: '接电问题',
    selected: false
  }

  // 限制进厂
  deviceRepairedIspush: any = {
    text: '限制进厂',
    selected: false
  }

  // 离线
  deviceOffline: any = {
    faultTypeName: '主机问题',
    programType: '201',
    text: '离线',
    selected: false
  }

  allSensorKeepValue() {
    this.isAllStraight = !this.isAllStraight
  }

  //显示安装位置
  showLocation(sensorChannel, value, Lens) {
    var installArray = [
      {
        index: 1,
        positionLMR: [
          {
            position: 'L',
            sensorChannel: []
          },
          {
            position: 'M',
            sensorChannel: []
          },
          {
            position: 'R',
            sensorChannel: []
          }
        ]
      },
      {
        index: 2,
        positionLMR: [
          {
            position: 'L',
            sensorChannel: []
          },
          {
            position: 'M',
            sensorChannel: []
          },
          {
            position: 'R',
            sensorChannel: []
          }
        ]
      },
      {
        index: 3,
        positionLMR: [
          {
            position: 'L',
            sensorChannel: []
          },
          {
            position: 'M',
            sensorChannel: []
          },
          {
            position: 'R',
            sensorChannel: []
          }
        ]
      },
      {
        index: 4,
        positionLMR: [
          {
            position: 'L',
            sensorChannel: []
          },
          {
            position: 'M',
            sensorChannel: []
          },
          {
            position: 'R',
            sensorChannel: []
          }
        ]
      },
      {
        index: 5,
        positionLMR: [
          {
            position: 'L',
            sensorChannel: []
          },
          {
            position: 'M',
            sensorChannel: []
          },
          {
            position: 'R',
            sensorChannel: []
          }
        ]
      },
      {
        index: 6,
        positionLMR: [
          {
            position: 'L',
            sensorChannel: []
          },
          {
            position: 'M',
            sensorChannel: []
          },
          {
            position: 'R',
            sensorChannel: []
          }
        ]
      }
    ] //安装位置
    let sensor
    let array = []
    this.checkChannel = []
    if (sensorChannel != 0) {
      for (let i = 0; i < sensorChannel.length; i++) {
        sensor = {
          mark: sensorChannel[i],
          text: sensorChannel[i],
          checked: false,
          isDisable: false
        }
        this.checkChannel.push(sensor)
        this.checkChannel.sort(this.compare('mark'))
        var checkChannelList = JSON.parse(JSON.stringify(this.checkChannel))
      }
    }
    var len
    if (value != null && value.length != 0) {
      len = value[value.length - 1].index
    } else {
      if (Lens == '') {
        Lens = 0
      }
      len = Lens
    }
    if (value != 0 && value != null) {
      for (let j = 0; j < installArray.length; j++) {
        for (let k = 0; k < value.length; k++) {
          if (installArray[j].index == value[k].index) {
            for (let f = 0; f < value[k].positionLMR.length; f++) {
              if (value[k].positionLMR[f].position == 'L') {
                installArray[j].positionLMR[0].sensorChannel = value[k].positionLMR[f].sensorChannel
                continue
              }
              if (value[k].positionLMR[f].position == 'M') {
                installArray[j].positionLMR[1].sensorChannel = value[k].positionLMR[f].sensorChannel
                continue
              }
              if (value[k].positionLMR[f].position == 'R') {
                installArray[j].positionLMR[2].sensorChannel = value[k].positionLMR[f].sensorChannel
                continue
              }
            }
            break
          }
        }
      }
      if (len > Lens || len == Lens) {
        if (len != 0) {
          installArray.splice(len, 6 - len)
        }
      } else {
        if (len != 0) {
          installArray.splice(Lens, 6 - Lens)
        }
      }

      this.installArray = this.deepClone(installArray)
    } else {
      if (len != 0) {
        installArray.splice(len, 6 - len)
      }
      this.installArray = this.deepClone(installArray)
    }

    this.showCheck(this.checkChannel)
  }

  showCheck(value) {
    var showCheckList = []
    for (var a = 0; a < this.installArray.length; a++) {
      for (var b = 0; b < this.installArray[a].positionLMR.length; b++) {
        for (var c = 0; c < this.installArray[a].positionLMR[b].sensorChannel.length; c++) {
          showCheckList.push(this.installArray[a].positionLMR[b].sensorChannel[c])
        }
      }
    }

    for (var i = 0; i < value.length; i++) {
      for (var j = 0; j < showCheckList.length; j++) {
        if (value[i].mark == showCheckList[j]) {
          value[i].isDisable = true
          break
        }
      }
    }

    this.checkChannel = this.deepClone(value)
  }

  // 编辑设备信息
  getEditDeviceInfo() {
    this.clearEditDeviceInfo()
    this.jsonApiService
      .http_obj('car/getCarInfoByDeviceId.html', { deviceId: this.selectedRow.deviceId })
      .subscribe(data => {
        if (data.success) {
          let result = data.data
          this.isAllStraight = result.isAllStraight ? true : false
          for (let item in this.page) {
            if (item == 'sensorChannel' && !result[item]) {
              result[item] = []
            }
            this.page[item] = result[item]
          }
          let resultChannel = []
          if (result.sensorChannel) {
            for (let item of result.sensorChannel) {
              if (item && item !== 'null') {
                resultChannel.push(item)
              }
            }
            result.sensorChannel = resultChannel
          }
          for (let item of this.deviceSensorArr) {
            item.checked = false
          }
          if (result.sensorChannel.length > 0) {
            for (var i = 0; i < result.sensorChannel.length; i++) {
              this.deviceSensorArr[result.sensorChannel[i] - 1].checked = true
            }
          }
          if (result.sensorProblemList) {
            if (result.sensorProblemList.length > 0) {
              //                      this.sensorSelectAll.selected = true;
              for (let sensor of result.sensorProblemList) {
                let sensorItem = sensor.sensorProblem.split('-')
                for (let item of this.sensorModuleList) {
                  if (item.text == sensorItem[0]) {
                    item.startTime = sensor.startTime
                    item.endTime = sensor.endTime
                    item.operator = sensor.operator
                    item.operatingTime = sensor.operatingTime
                    item.sensorProblem = sensor.sensorProblem
                    for (let lis of item.child) {
                      if (lis.text == sensorItem[1]) {
                        lis.selected = true
                        item.selected = true
                      } else {
                        lis.selected = false
                      }
                    }
                  }
                }
              }
            }
          }
          if (result.gpsProblemEntity) {
            let gps = result.gpsProblemEntity
            this.GPSProblemList.startTime = gps.startTime
            this.GPSProblemList.endTime = gps.endTime
            this.GPSProblemList.operator = gps.operator
            this.GPSProblemList.operatingTime = gps.operatingTime
            this.GPSProblemList.gpsProblem = gps.gpsProblem
            for (let item of this.GPSModuleList) {
              if (item.text == gps.gpsProblem) {
                item.selected = true
                this.GPSProblemList.selected = true
              } else {
                item.selected = false
              }
            }
          }
          $('#useTypeSelect').val(this.page.useTypeL2).trigger('change')

          this.ChannelLen = data.data.carAxleAmount
          //选中通道值
          this.showLocation(data.data.sensorChannel, data.data.sensorPosition, data.data.carAxleAmount)

          let sensor1, sensor2
          this.sensorAxleFront = []
          this.sensorAxleAfter = []
          var AxleFrontList = JSON.parse(JSON.stringify(this.sensorAxleFront))
          var AxleAfterList = JSON.parse(JSON.stringify(this.sensorAxleAfter))
          // this.sensorAxleAfter = this.deepClone(this.sensorAxleFront); //深拷贝

          for (let j = 0; j < data.data.sensorChannel.length; j++) {
            if (data.data.sensorAxle == null || data.data.sensorAxle.length == 0) {
              sensor1 = {
                mark: data.data.sensorChannel[j],
                text: data.data.sensorChannel[j],
                checked: false,
                isDisable: false
              }

              AxleFrontList.push(sensor1)
              AxleAfterList.push(sensor1)
            } else {
              for (let k = 0; k < data.data.sensorAxle.length; k++) {
                if (data.data.sensorAxle[k] == 0 && k == j) {
                  sensor1 = {
                    mark: data.data.sensorChannel[j],
                    text: data.data.sensorChannel[j],
                    checked: false,
                    isDisable: false
                  }
                  AxleFrontList.push(sensor1)
                  AxleAfterList.push(sensor1)
                } else if (data.data.sensorAxle[k] == 1 && k == j) {
                  sensor1 = {
                    mark: data.data.sensorChannel[j],
                    text: data.data.sensorChannel[j],
                    checked: true,
                    isDisable: false
                  }
                  sensor2 = {
                    mark: data.data.sensorChannel[j],
                    text: data.data.sensorChannel[j],
                    checked: false,
                    isDisable: true
                  }
                  AxleFrontList.push(sensor1)
                  AxleAfterList.push(sensor2)
                } else if (data.data.sensorAxle[k] == 2 && k == j) {
                  sensor1 = {
                    mark: data.data.sensorChannel[j],
                    text: data.data.sensorChannel[j],
                    checked: false,
                    isDisable: true
                  }
                  sensor2 = {
                    mark: data.data.sensorChannel[j],
                    text: data.data.sensorChannel[j],
                    checked: true,
                    isDisable: false
                  }
                  AxleFrontList.push(sensor1)
                  AxleAfterList.push(sensor2)
                }
              }
            }
            this.sensorAxleFront = this.deepClone(AxleFrontList) //深拷贝
            this.sensorAxleAfter = this.deepClone(AxleAfterList) //深拷贝
          }
        } else {
          this.jsonApiService.message(data.message)
        }
      })

    //算法问题清空
    for (let lis of this.algorithmQuestionList) {
      lis.selected = false
    }
  }

  // 清空编辑设备信息表
  clearEditDeviceInfo() {
    this.GPSSelectAll.selected = false
    this.sensorSelectAll.selected = false
    for (let item in this.page) {
      this.page[item] = ''
      if (item == 'sensorChannel') {
        this.page[item] = []
      }
    }
    for (let item of this.GPSModuleList) {
      item.selected = false
    }
    for (let item of this.sensorModuleList) {
      item.startTime = ''
      item.endTime = ''
      item.operator = ''
      item.operatingTime = ''
      item.sensorProblem = ''
      for (let lis of item.child) {
        lis.selected = false
      }
    }
    for (let item of this.deviceSensorArr) {
      item.checked = false
    }
    this.GPSProblemList = {
      startTime: '',
      endTime: '',
      operator: '',
      operatingTime: '',
      gpsProblem: '',
      selected: false
    }
    // 重置表单的数据
    $('#sensorAmount').val('')
    $('#useTypeSelect').val(null).trigger('change')
  }

  //添加设备维修
  addDeviceRepaired() {
    let data: any = []
    let sensorProblem: string = '',
      gpsProblem: string = '',
      sensorFlag: any,
      gpsFlag: any
    if (this.sensorSelectAll.selected) {
      sensorFlag = 1
      for (let item of this.sensorModuleList) {
        for (let lis of item.child) {
          if (lis.selected) {
            if (sensorProblem) {
              sensorProblem += ',' + item.text + '-' + lis.text
            } else {
              sensorProblem += item.text + '-' + lis.text
            }
          }
        }
      }
    } else {
      sensorFlag = 0
    }
    if (this.GPSSelectAll.selected) {
      gpsFlag = 1
      for (let item of this.GPSModuleList) {
        if (item.selected) {
          gpsProblem = item.text
        }
      }
    } else {
      gpsFlag = 0
    }
    if (sensorProblem) {
      let sensorObj = {
        programType: '202',
        deviceId: this.selectedRow.deviceId,
        carNumber: this.selectedRow.carNumber,
        faultTypeName: '传感器问题',
        faultTime: this.startTime_chart,
        faultPhenomenon: sensorProblem.split(','),
        isPush: this.deviceRepairedIspush.selected ? '1' : ''
      }
      data.push(sensorObj)
    }
    if (gpsProblem) {
      let gpsObj = {
        programType: '203',
        deviceId: this.selectedRow.deviceId,
        carNumber: this.selectedRow.carNumber,
        faultTypeName: 'GPS问题',
        faultTime: this.startTime_chart,
        faultPhenomenon: gpsProblem.split(','),
        isPush: this.deviceRepairedIspush.selected ? '1' : ''
      }
      data.push(gpsObj)
    }
    // 因为离线和接电问题是同一种类型的问题，所以在这里进行合并处理 faultPhenomenon: ['离线', '接电问题']
    if (this.deviceOffline.selected || this.deviceContact.selected) {
      const offlineObj = {
        programType: this.deviceOffline.programType,
        deviceId: this.selectedRow.deviceId,
        carNumber: this.selectedRow.carNumber,
        faultTypeName: '主机问题',
        faultTime: this.startTime_chart,
        // faultPhenomenon: this.deviceOffline.text.split(','),
        faultPhenomenon: [],
        isPush: this.deviceRepairedIspush.selected ? '1' : ''
      }
      if (this.deviceOffline.selected) {
        offlineObj.faultPhenomenon.push(this.deviceOffline.text)
      }
      if (this.deviceContact.selected) {
        offlineObj.faultPhenomenon.push(this.deviceContact.text)
      }
      data.push(offlineObj)
    }
    if (!sensorProblem && !gpsProblem && !this.deviceOffline.selected && !this.deviceContact.selected) {
      this.jsonApiService.message('请选择故障类型')
      return
    }
    let reqdata = 'list=' + JSON.stringify(data) + '&sensor=' + sensorFlag + '&gps=' + gpsFlag
    // 限制车辆的“开始时间” 要小于“ 维修时间”，做个弹框，提示内容：“ 粤B33322 于[xxxx-xx-xx xx:xx:xx]已维修，请与[xxx]（维修人） 核实维修情况 ”，是，继续录入维修，否，取消该次操作
    let selectTime = new Date(this.startTime_chart).getTime()
    let lastServiceTime = this.haveRepaireObj ? this.haveRepaireObj.repairedTime : null
    let lastTime = new Date(lastServiceTime).getTime()
    // 点击了限制进厂 并且 选择的时间小于最后一次维修的时间 就进行提示
    if (this.deviceRepairedIspush.selected && selectTime < lastTime) {
      let carNumber = this.haveRepaireObj.carNumber
      let repairedUser = this.haveRepaireObj.repairedUserName
      // 提示
      this.notificationService.smartMessageBox(
        {
          title: '提示',
          content: carNumber + '于 [' + lastServiceTime + '] 已维修，请与 [' + repairedUser + ']（维修人）核实维修情况',
          buttons: '[继续录入][取消]'
        },
        ButtonPressed => {
          if (ButtonPressed === '继续录入') {
            // 继续录入就直接录入
            this.jsonApiService.http('deviceRepaired/insertDeviceRepairedBatch.html', reqdata).subscribe(data => {
              this.jsonApiService.message(data.message)
            })
          }
          if (ButtonPressed === '取消') {
            return
          }
        }
      )
    } else {
      this.jsonApiService
        .http('deviceRepaired/validateRecord.html', 'deviceId=' + this.selectedRow.deviceId)
        .subscribe(result => {
          if (result.valid) {
            this.jsonApiService.confirm_message(result.message + '确认要继续提交?').then(() => {
              this.jsonApiService.http('deviceRepaired/insertDeviceRepairedBatch.html', reqdata).subscribe(data => {
                this.jsonApiService.message(data.message)
              })
            })
          } else {
            this.jsonApiService.http('deviceRepaired/insertDeviceRepairedBatch.html', reqdata).subscribe(data => {
              this.jsonApiService.message(data.message)
            })
          }
        })
    }
  }
  //更新设备状态
  updataDeviceStatus() {
    let sensorProblem: string = '',
      gpsProblem: string = '',
      sensorFlag: any,
      gpsFlag: any
    for (let item of this.sensorModuleList) {
      for (let lis of item.child) {
        if (lis.selected) {
          if (sensorProblem) {
            sensorProblem += ',' + item.text + '-' + lis.text
          } else {
            sensorProblem += item.text + '-' + lis.text
          }
        }
      }
    }
    for (let item of this.GPSModuleList) {
      if (item.selected) {
        gpsProblem = item.text
      }
    }
    if (this.sensorSelectAll.selected) {
      sensorFlag = 1
    } else {
      sensorFlag = 0
    }
    if (this.GPSSelectAll.selected) {
      gpsFlag = 1
    } else {
      gpsFlag = 0
    }
    if (!this.selectedRow.deviceId) {
      this.jsonApiService.message('请选择设备')
      return
    }
    if (!sensorFlag && !gpsFlag && !this.isAllStraight) {
      this.jsonApiService.message('请选择问题分类')
      return
    }
    this.jsonApiService.confirm_message('您确定要更新设备状态？').then(() => {
      let reqdata = {
        isAllStraight: this.isAllStraight ? 1 : 0,
        sensor: sensorFlag,
        gps: gpsFlag,
        deviceId: this.selectedRow.deviceId,
        sensorProblem: sensorProblem,
        gpsProblem: gpsProblem,
        startDate: this.startTime_chart,
        endDate: this.endTime_chart
      }
      this.jsonApiService.http_obj('car/updateCarStatus.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.getEditDeviceInfo()
        }
      })
    })
  }
  //加载传感器数据
  loadSensorModule(data) {
    this.sensorModuleList = []
    for (let item of data) {
      let obj = {
        flag: item.flag,
        value: item.value,
        text: '传感器' + item.value,
        faultTypeName: '传感器问题',
        programType: '202',
        startTime: '',
        endTime: '',
        operator: '',
        operatingTime: '',
        sensorProblem: '',
        selected: false,
        isFront: item.isFront,
        child: [
          {
            text: '正负52万',
            code: 'SP1',
            selected: false
          },
          {
            text: '偶尔52万',
            code: 'SP1-1',
            selected: false
          },
          {
            text: '经常52万',
            code: 'SP1-2',
            selected: false
          },
          {
            text: '乱跳',
            code: 'SP2',
            selected: false
          },
          {
            text: '形变小',
            code: 'SP3',
            selected: false
          },
          {
            text: '方向反',
            code: 'SP4',
            selected: false
          },
          {
            text: '平直',
            code: 'SP5',
            selected: false
          }
        ]
      }
      this.sensorModuleList.push(obj)
    }
  }

  // GPS全选框
  GPSSelectAllClick() {
    this.GPSSelectAll.selected = !this.GPSSelectAll.selected
  }
  // 提交GPS问题,单个GPS
  updateGPSProblem() {
    let gpsProblem: string = ''
    for (let item of this.GPSModuleList) {
      if (item.selected) {
        gpsProblem = item.text
      }
    }
    if (!gpsProblem) {
      this.jsonApiService.message('请选择GPS问题')
      return
    }
    let reqdata = {
      deviceId: this.selectedRow.deviceId,
      startTime: $('#datetimepicker3').val(),
      endTime: $('#datetimepicker4').val(),
      gpsProblem: gpsProblem
    }
    this.jsonApiService.http_obj('car/updateGpsProblem.html', reqdata).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        this.getEditDeviceInfo()
      }
    })
  }

  // GPS列表选择
  GPSLisSelected(code) {
    for (let lis of this.GPSModuleList) {
      if (lis.code == code) {
        lis.selected = !lis.selected
        lis.selected ? (this.GPSSelectAll.selected = true) : (this.GPSSelectAll.selected = false)
      } else {
        lis.selected = false
      }
    }
  }

  deviceOfflineClick() {
    this.deviceOffline.selected = !this.deviceOffline.selected
  }

  deviceContactClick() {
    this.deviceContact.selected = !this.deviceContact.selected
  }

  deviceRepairedIspushClick() {
    this.deviceRepairedIspush.selected = !this.deviceRepairedIspush.selected
  }

  //选择算法问题
  algorithmLisSelected(text) {
    for (let lis of this.algorithmQuestionList) {
      if (lis.text == text) {
        lis.selected = !lis.selected
      } else {
        lis.selected = false
      }
    }
  }
  //算法问题提交
  updataOrderStatus() {
    if (!this.selectedRow.deviceId) {
      this.jsonApiService.message('先选择车辆...')
      return
    }
    var proType2
    for (var i = 0; i < this.algorithmQuestionList.length; i++) {
      if (this.algorithmQuestionList[i].selected == true) {
        proType2 = this.algorithmQuestionList[i].programType
      }
    }

    if (!proType2) {
      this.jsonApiService.message('请选择问题分类')
      return
    }

    if (!this.startTime_chart || !this.endTime_chart) {
      this.jsonApiService.message('开始时间和结束时间不能为空...')
      return
    }

    this.jsonApiService
      .http('realtime/getRealTimeData.html', 'deviceId=' + this.selectedRow.deviceId)
      .subscribe(result => {
        let params = {
          programType: proType2,
          deviceId: this.selectedRow.deviceId,
          version: result.data.version ? result.data.version : '',
          startDate: this.startTime_chart,
          endDate: this.endTime_chart,
          reason: '',
          exceptionType: '1',
          coefficient: result.data.coef ? result.data.coef : ''
        }
        let reqdata = ''
        for (let keys in params) {
          reqdata = reqdata + keys + '=' + params[keys] + '&'
        }
        reqdata = reqdata.substring(0, reqdata.length - 1)
        this.jsonApiService.http('dataExceptionRecord/addDataException.html', reqdata).subscribe(result2 => {
          this.jsonApiService.message(result2.message)
        })
      })
  }

  // 编辑页面的数据
  carTypeList = carTypeListObj.carTypeList
  // 打开编辑窗口
  editDeviceInfo(modal) {
    if (!this.selectedRow.deviceId) {
      this.jsonApiService.message('请选择设备')
      return
    }
    modal.show()
    this.getEditDeviceInfo()
  }

  sensorSelected(data) {
    this.page.sensorType = data.sensorType
  }

  /* 传感器通道 前轴 后轴  通道 */

  //通道 前
  sensorAxleFrontChange(item, e) {
    let sensorAxleList = []
    for (let i = 0; i < this.sensorAxleFront.length; i++) {
      if (item.mark == this.sensorAxleFront[i].mark) {
        if (e.target.className.indexOf('wayCheck') != -1) {
          this.sensorAxleFront[i].checked = false
          this.sensorAxleAfter[i].isDisable = false
        } else {
          this.sensorAxleFront[i].checked = true
          this.sensorAxleAfter[i].isDisable = true
        }
      }
    }

    for (let j = 0; j < this.sensorAxleAfter.length; j++) {
      if (!this.sensorAxleAfter[j].checked && !this.sensorAxleAfter[j].isDisable) {
        sensorAxleList.push(0)
      } else if (this.sensorAxleAfter[j].checked) {
        sensorAxleList.push(2)
      } else if (this.sensorAxleAfter[j].isDisable) {
        sensorAxleList.push(1)
      }
    }
    this.page.sensorAxle = this.deepClone(sensorAxleList)
  }

  //通道 后
  sensorAxleAfterChange(item, e) {
    let sensorAxleList = []
    for (let i = 0; i < this.sensorAxleAfter.length; i++) {
      if (item.mark == this.sensorAxleAfter[i].mark) {
        if (e.target.className.indexOf('wayCheck') != -1) {
          this.sensorAxleAfter[i].checked = false
          this.sensorAxleFront[i].isDisable = false
        } else {
          this.sensorAxleAfter[i].checked = true
          this.sensorAxleFront[i].isDisable = true
        }
      }
    }

    for (let j = 0; j < this.sensorAxleFront.length; j++) {
      if (!this.sensorAxleFront[j].checked && !this.sensorAxleFront[j].isDisable) {
        sensorAxleList.push(0)
      } else if (this.sensorAxleFront[j].checked) {
        sensorAxleList.push(1)
      } else if (this.sensorAxleFront[j].isDisable) {
        sensorAxleList.push(2)
      }
    }
    this.page.sensorAxle = this.deepClone(sensorAxleList)
  }

  //车轴数量出现安装位置
  carAxleAmountChange(value) {
    if (this.page.sensorAxle == null || this.page.sensorAxle.length == 0) {
      this.page.sensorAxle = []
      if (this.page.sensorChannel.length != 0) {
        for (var j = 0; j < this.page.sensorChannel.length; j++) {
          let mun = '0'
          this.page.sensorAxle.push(mun)
        }
      }
    }

    var array = []
    if (isNaN(value) == true) {
      this.jsonApiService.message('请输入数字')
      $('#carAxleAmount').val('')
      this.page.carAxleAmount = ''
      return
    } else if (value > 6) {
      this.jsonApiService.message('车轴数量不能大于6')
      $('#carAxleAmount').val('')
      this.page.carAxleAmount = ''
      return
    } else {
      if (value == '0') {
        this.jsonApiService.message('车轴数量不能为0')
        $('#carAxleAmount').val('')
        this.page.carAxleAmount = ''
        return
      } else if (value == '') {
        if (this.ChannelLen == 0 && this.page.carAxleAmount == '') {
          this.showLocation(this.page.sensorChannel, this.page.sensorPosition, value)
        } else {
          for (var i = 0; i < 6; i++) {
            var positionLMR = {
              index: i + 1,
              positionLMR: [
                {
                  position: 'L',
                  sensorChannel: []
                },
                {
                  position: 'M',
                  sensorChannel: []
                },
                {
                  position: 'R',
                  sensorChannel: []
                }
              ]
            }
            array.push(positionLMR)
          }
          this.installArray = this.deepClone(array)
          this.clearcheckChannel()
        }
      } else if (value == this.ChannelLen) {
        this.showLocation(this.page.sensorChannel, this.page.sensorPosition, value)
      } else {
        for (var i = 0; i < value; i++) {
          var positionLMR = {
            index: i + 1,
            positionLMR: [
              {
                position: 'L',
                sensorChannel: []
              },
              {
                position: 'M',
                sensorChannel: []
              },
              {
                position: 'R',
                sensorChannel: []
              }
            ]
          }
          array.push(positionLMR)
        }
        this.installArray = this.deepClone(array)
        this.clearcheckChannel()
      }
    }
  }

  //清除安装位置轴数选中
  clearcheckChannel() {
    for (var a = 0; a < this.checkChannel.length; a++) {
      this.checkChannel[a].isDisable = false
    }
  }

  //删除选中的传感器
  cancelChannel(index, type, channel) {
    let valueList
    if (type == 'left') {
      valueList = this.installArray[index - 1].positionLMR[0].sensorChannel
      for (let i = 0; i < valueList.length; i++) {
        if (valueList[i] == channel) {
          valueList.splice(i, 1)
        }
      }
      this.installArray[index - 1].positionLMR[0].sensorChannel = this.deepClone(valueList)
    } else if (type == 'middle') {
      valueList = this.installArray[index - 1].positionLMR[1].sensorChannel
      for (let j = 0; j < valueList.length; j++) {
        if (valueList[j] == channel) {
          valueList.splice(j, 1)
        }
      }
      this.installArray[index - 1].positionLMR[1].sensorChannel = this.deepClone(valueList)
    } else if (type == 'right') {
      valueList = this.installArray[index - 1].positionLMR[2].sensorChannel
      for (let k = 0; k < valueList.length; k++) {
        if (valueList[k] == channel) {
          valueList.splice(k, 1)
        }
      }
      this.installArray[index - 1].positionLMR[2].sensorChannel = this.deepClone(valueList)
    }

    for (let l = 0; l < this.checkChannel.length; l++) {
      if (this.checkChannel[l].mark == channel) {
        this.checkChannel[l].isDisable = false
      }
    }
  }

  axisType: any = '' //打开那个方向传感器轴
  axisIndex: any = '' //打开那个传感器轴
  //添加传感器通道
  addinstall(index, type, modal) {
    this.axisType = type
    this.axisIndex = index
    if (this.page.sensorAmount) {
      modal.show()
    } else {
      this.jsonApiService.message('请先选择传感器')
    }
  }

  // gps选项
  gpsOptions = allSelectOptionsObj.gpsOptions

  //gps天线change回调
  gpsAntennaChange(val) {
    this.page.gpsAntenna = val

    for (var i = 0; i < allSelectOptionsObj.gsmOptions.length; i++) {
      if (allSelectOptionsObj.gsmOptions[i].text == val) {
        this.page.gsmAntenna = val
      }
    }
  }

  //gsm天线change回调
  gsmAntennaChange(val) {
    this.page.gsmAntenna = val

    for (var i = 0; i < allSelectOptionsObj.gpsOptions.length; i++) {
      if (allSelectOptionsObj.gpsOptions[i].text == val) {
        this.page.gpsAntenna = val
      }
    }
  }

  // 提交表单数据
  submitEditDeciceModal(modal) {
    var reqdata = new FormData()
    this.page.useTypeL2 = $('#useTypeSelect').val()
    this.page.useTypeL1 = $('#useTypeSelect').val().slice(0, 2)
    if (this.page.sensorChannel) {
      for (let iems of this.page.sensorChannel) {
        if (!iems) iems = ''
      }
    } else {
      this.page.sensorChannel = []
    }
    if (this.page.sensorAxle == null || this.page.sensorAxle.length == 0) {
      if (this.sensorAxleAfter.length != 0) {
        let sensorAxleList = []
        for (let j = 0; j < this.sensorAxleAfter.length; j++) {
          sensorAxleList.push(0)
        }
        this.page.sensorAxle = this.deepClone(sensorAxleList)
      }
    }

    for (let item in this.page) {
      if (item == 'sensorPosition') {
        this.page.sensorPosition = this.filterPosition(this.installArray)
        reqdata.append('sensorPositionJson', JSON.stringify(this.page.sensorPosition))
      } else {
        reqdata.append(item, common.stringTrim(this.page[item]))
      }
    }
    this.jsonApiService.form_http('car/edit.html', reqdata).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        this.getEditDeviceInfo()
        this.getDeviceBasicInfo()
        modal.hide()
      }
    })
  }

  //过滤通道数据
  filterPosition(value) {
    var List = []
    var ListParant = []
    this.page.sensorPosition = []
    for (let j = 0; j < value.length; j++) {
      if (
        value[j].positionLMR[0].sensorChannel.length != 0 &&
        value[j].positionLMR[1].sensorChannel.length != 0 &&
        value[j].positionLMR[2].sensorChannel.length != 0
      ) {
        List.push(value[j])
      } else {
        for (let a = 0; a < value[j].positionLMR.length; a++) {
          if (value[j].positionLMR[a].sensorChannel.length != 0) {
            ListParant.push(value[j].positionLMR[a])
          }
        }
        if (ListParant.length != 0) {
          var positionLMR = {
            index: j + 1,
            positionLMR: ListParant
          }
          List.push(positionLMR)
        }

        // if(ListParant.length != 0){List.push(ListParant);}
        ListParant = []
        continue
      }
    }
    return List
  }

  //深拷贝浅拷贝
  deepClone(obj) {
    let objClone = Array.isArray(obj) ? [] : {}
    if (obj && typeof obj === 'object') {
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          //判断ojb子元素是否为对象，如果是，递归复制
          if (obj[key] && typeof obj[key] === 'object') {
            objClone[key] = this.deepClone(obj[key])
          } else {
            //如果不是，简单复制
            objClone[key] = obj[key]
          }
        }
      }
    }
    return objClone
  }

  /**
   * 传感器白名单相关功能
   */
  sensorWhitelistParams = {
    startTime: '',
    endTime: '',
    companyId: '',
    companyName: '',
    status: '0' as '0' | '1' | '', // 状态（0生效 1失效） '' 全部
    searchKey: ''
  }

  sensorWhitelistTableData = []
  whitelistPageSize = 10
  whitelistCurPage = 1
  whitelistTotal = 0

  handleSensorWhitelistClick(modal) {
    this.sensorWhitelistParams = {
      startTime: '',
      endTime: '',
      companyId: '',
      companyName: '',
      status: '0',
      searchKey: ''
    }
    this.whitelistPageSize = 10
    this.whitelistTotal = 0
    this.handleWhitelistSearch()
    // notice 不能使用 $('#id').modal('show')
    // 可以展示隐藏，但是会导致 select2 下拉框无法聚焦
    modal.show()
  }

  //删除所选时间
  delSensorDate() {
    this.sensorWhitelistParams.startTime = ''
    this.sensorWhitelistParams.endTime = ''
    $('#sensorWhitelistDatepicker1').val('').change()
    $('#sensorWhitelistDatepicker2').val('').change()
    $('#sensorWhitelistDatepicker2').datetimepicker('setStartDate', null)
    $('#sensorWhitelistDatepicker1').datetimepicker('setEndDate', null)
  }

  //分页回调
  whitelistPaginate(e) {
    this.whitelistCurPage = e.page + 1
    this.whitelistPageSize = e.rows
    this.whitelistRequest()
  }
  handleWhitelistSearch() {
    this.whitelistCurPage = 1
    this.whitelistRequest()
  }

  // 数据导出
  handleSensorWhitelistExport() {
    if (!this.sensorWhitelistParams.startTime || !this.sensorWhitelistParams.endTime) {
      this.jsonApiService.message('请先选择时间区间再进行导出')
      return
    }
    const param = {
      pageSize: this.whitelistPageSize,
      nowPage: this.whitelistCurPage,
      parameters: {
        ...this.sensorWhitelistParams
      },
      isExport: 1
    }
    common.exprotDataFile(param, 'gridPager', config.BaseURL + 'deviceCheck/sensorCheckWhiteList.html')
  }

  cancelSensorWhitelist(row) {
    this.jsonApiService.confirm_message('此操作将取消本条传感器检测白名单,确认要取消?').then(() => {
      this.jsonApiService.http_obj('deviceCheck/cancelSensorCheckWhiteList.html', { id: row.id }).subscribe(data => {
        this.jsonApiService.message(data.message);
        if (data.success) {
          this.whitelistRequest()
        }
      })
    })
  }

  whitelistRequest() {
    const parameters = this.sensorWhitelistParams
    // delete parameters.startTime
    // delete parameters.endTime
    const param = {
      pageSize: this.whitelistPageSize,
      nowPage: this.whitelistCurPage,
      parameters
    }
    const reqdata = 'gridPager=' + JSON.stringify(param)
    this.jsonApiService.http('deviceCheck/sensorCheckWhiteList.html', reqdata).subscribe(data => {
      this.sensorWhitelistTableData = data.exhibitDatas
      this.whitelistTotal = data.recordCount
    })
  }

  // 设置厂区在线的公司选择回调
  onSensorWhitelistSelected(data) {
    // 请求验证接口
    this.sensorWhitelistParams.companyId = data.companyId
    this.sensorWhitelistParams.companyName = data.companyName
  }

  handleWhitelistAddClick(modal) {
    $("#setFrequencyFrom").data('bootstrapValidator').resetForm();
    this.isSensorWhitelistCreate = true
    modal.show()
  }

  closeModal(modal) {
    modal.hide()
  }

  // 传感器白名单
  sensorBypassValidatorOptions = {
    excluded: [":disabled"],
    fields: {
      deviceId: {
        validators: {
          notEmpty: {
            message: '请选择车辆'
          }
        }
      },
      status: {
        validators: {
          notEmpty: {
            message: '请选择白名单时长'
          }
        }
      },
      days: {
        validators: {
          notEmpty: {
            message: '请输入自定义天数'
          }
        }
      },
    }
  }

  sensorBypassModel = {
    id: '',
    deviceId: '',
    carNumber: '',
    status: '', // 白名单状态（1长期 2自定义天数 3取消白名单）
    days: null,
    describe: ''
  }

  initWhitelistCarSelect() {
    const that = this;
    $("#sensorBypassSelect").select2({
      language: "zh-CN",
      minimumInputLength: 4,
      allowClear: false,
      placeholder: "请选择",
      dropdownParent: $('#sensorBypassModal'),
      ajax: {
        url: config.BaseURL + "stats/carListByCarNumber.html",
        dataType: 'json',
        delay: 50,
        method: "POST",
        xhrFields: { withCredentials: true },
        data: function (params) {
          return { "carNumber": params.term };
        },
        processResults: function (res, params) {
          const options = [];
          const data = res.data
          // 小于10个数量才判断重复
          if (data.length <= 10) {
            const arr = []
            const sameCar = []
            // 判断相同的车牌号
            for (let i = 0; i < data.length; i++) {
              const car = data[i];
              if (arr.indexOf(car.carNumber) != -1) {
                sameCar.push(car.carNumber)
              } else {
                arr.push(car.carNumber);
              }
            }
            $(data).each(function (_, car) {
              if (sameCar.indexOf(car.carNumber) != -1) {
                options.push({
                  id: car.deviceId,
                  text: car.carNumber + "[" + car.parentName + "]"
                })
              } else {
                options.push({
                  id: car.deviceId,
                  text: car.carNumber
                })
              }
            });
          } else {
            $(data).each(function (_, car) {
              options.push({
                id: car.deviceId,
                text: car.carNumber
              })
            });
          }
          return {
            results: options //获取查询后的结果
          };
        },
        cache: true
      },
      templateResult: function (state) {
        if (!state.id) { return state.text; }
        var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
        return $state;
      },
    }).on("select2:select", function (e) {
      const data = e.params.data;
      that.sensorBypassModel.deviceId = data.id;
      if (data.text.indexOf('[') > 0) {
        that.sensorBypassModel.carNumber = data.text.split('[')[0];
      } else {
        that.sensorBypassModel.carNumber = data.text;
      }
    });
  }

  isSensorWhitelistCreate = true

  handleSensorBypassSetting(modal, row) {
    $("#setFrequencyFrom").data('bootstrapValidator').resetForm();
    this.isSensorWhitelistCreate = false
    modal.show()
    const { status, id, deviceId, carNumber, cancelTime, describe } = row
    // 已取消
    if (status === 1) {
      this.sensorBypassModel = {
        id,
        deviceId,
        carNumber,
        status: '3', // 白名单状态（1长期 2自定义天数 3取消白名单）
        days: '',
        describe
      }
      return
    }
    // 重置数据，写入车辆信息
    this.sensorBypassModel = {
      id,
      deviceId,
      carNumber,
      status: cancelTime ? '2' : '1', // 白名单状态（1长期 2自定义天数 3取消白名单）
      days: cancelTime || '',
      describe
    }

    // $('#sensorBypassSelect').val(deviceId).trigger('change');
  }
  //自定义限制,校验非空值,默认6小时,不允许为空
  sensorBypassInputChange() {
    this.sensorBypassModel.days = Math.abs(Math.floor(this.sensorBypassModel.days))
  }
  // 时长选中项改变，清空天数
  handleSersonBypassStatusChange() {
    this.sensorBypassModel.days = ''
  }

  editSensorBypassModal(modal) {
    $('#setFrequencyFrom').bootstrapValidator('validate') //开启验证
    let isValid = $('#setFrequencyFrom').data('bootstrapValidator').isValid() //验证是否通过
    // select 2 隐藏也会校验
    if (isValid || (!this.isSensorWhitelistCreate && this.sensorBypassModel.status)) {
      if (this.sensorBypassModel.status === '2' && !this.sensorBypassModel.days) {
        this.jsonApiService.message('请输入自定义天数')
        return
      }
      const sensorBypassModel = this.sensorBypassModel
      // 过滤空数据
      const data = Object.keys(sensorBypassModel).reduce((prev, key) => {
        const val = sensorBypassModel[key]
        if (val) {
          prev[key] = val
        }
        return prev
      }, {})
      this.jsonApiService.http_obj('deviceCheck/addSensorCheckWhiteList.html', data).subscribe(data => {
        this.jsonApiService.message(data.message);
        if (data.success) {
          this.sensorBypassModel = {
            id: '',
            deviceId: '',
            carNumber: '',
            status: '', // 白名单状态（1长期 2自定义天数 3取消白名单）
            days: null,
            describe: ''
          }
          this.whitelistRequest()
          modal.hide()
        }
      })
    }
  }


}
